C Fiile Writer不会写我给它的字符
C++ fiile writer does not write characters that I give it
我目前正在为我的计算机组织课程开展一个项目,我的教授决定将我们投入到一个C 项目中,没有任何上课时间或经验。该项目的目的是创建一个可以使用运行长度编码来压缩或解压缩文件的程序,并为我们提供了一个代码框架。我目前正在尝试编写编码函数,这就是我到目前为止所拥有的。请记住,我在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内置的调试套件来运行它,但是由于某种原因,它说在我以调试模式运行时不存在测试文件。
关于3 z的未计数:您的代码仅在处理字符时输出数据。在所有字符都由您的for循环处理后,您需要再次转储CurrentChar和Charcount。
如果要将一个数字写入文件,您可以做
之类的事情putc (charCount + 48, fp)
这仅适用于整数0-9。对于较大的数字,您需要获取每个数字并向其添加48个。
尽管从查看您的代码来看,Charcount变量将始终为1。我认为代码的最后一行可能是
charCount += 1
另一个选项是:
putc('0' + charCount, outfile);
或
putc('0' + 9, outfile);
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- C Fiile Writer不会写我给它的字符