C++ 文件编写器不写我给它的字符

C++ fiile writer does not write characters that I give it

我目前正在为我的计算机组织 class 做一个项目,我的教授决定让我们一头扎进一个 C++ 项目,除了按位运算符和之前没有 class 时间或经验内存指针。该项目的目标是创建一个可以使用 运行 长度编码压缩或解压缩文件的程序,我们获得了一个代码框架来使用。我目前正在尝试编写 Encode 函数,这就是我目前所拥有的。请记住,我以前完全没有使用 C 或 C++ 的经验。

void compress( char* data, int count, FILE* outfile )
{
// TODO: compress the data instead of just writing it out to the file
char currentChar = data[0];
int charCount;
charCount = 0;

for (int i=0; i<count; ++i)
{
   if(data[i] == currentChar)
   {
       charCount++;
   }
   else if(data[i] != currentChar)
   {
      if(charCount > 9)
      {
           while(charCount > 9)
           {
               putc(currentChar, outfile); // write the current char to the file
               putc(9, outfile); // write 9 to the file
               charCount -= 9;
           }
           putc( currentChar, outfile ); // write the current char to the file
           putc( charCount, outfile); // write the number of currentChar to the file
       }
       else
       {
           putc( currentChar, outfile ); // write the current char to the file
           putc( charCount, outfile); // write the number of currentChar to the file
       }

       // reset the currentChar and charCount variables
       currentChar = data[i];
       charCount = 1;
      }

   }
}

这段代码给出的输出如下: x x(未知字符)y(未知字符)

什么时候应该: x9x1y4z3

我到底做错了什么?就我(极其有限)的知识而言,这应该是正确的。但同样,我对 C++ 完全陌生(我唯一的其他编码经验是 Python 和 Java)。

编辑: 好的,数字书写正确。现在的输出是:x9x1y4,这几乎是正确的。 Bot 现在压缩代码仍然忽略了我在测试文件末尾的三个 Z。我会通过 Eclipse 内置的调试套件 运行 它,但出于某种原因,当我在调试模式下 运行 它说测试文件不存在。

如果你想在文件中写入一个数字,你可以像

putc (charCount + 48, fp)

这仅适用于整数 0-9。对于更大的数字,您需要获取每个数字并将其加 48。

尽管从您的代码来看,charCount 变量将始终为 1。我认为代码的最后一行可能是

charCount += 1

另一种选择是:

putc('0' + charCount, outfile);

putc('0' + 9, outfile);

关于3个z不被计算在内:您的代码仅在处理字符时输出数据。在 for 循环处理完所有字符后,您需要再次转储 currentChar 和 charCount。