将 CRC 数据写入 .txt 文件

Writing CRC data to .txt file

这看起来应该是一个基本的C++过程,但我对数据输出不熟悉。

当我打印数据而不输出到文本文件时,我得到了正确的值。

example: 00150017000 181

打印到文本文件时,这是我得到的:

11161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116

这是我的代码:

ofstream myfile;
myfile.open("C:\CRC.txt");
for (i = 0; i < 200; i++, id++)
{
    myfile << sprintf(idstring, "%011d", id);
    myfile << printf("%s %03d\n", idstring, computeCrc(idstring));
}
myfile.close();

其他一切正常,我知道 CRC 已正确生成。只需要获得正确的输出即可。

我能够通过将“> CRC.txt”添加到调试属性命令参数来将控制台屏幕输出到文本文件,但我只是想知道如何将 ofstream 方法合并到其中。

提前致谢。

您没有将您认为保存的内容保存到文件中。首先保存 sprintf() 函数的结果,在您的情况下为 11。然后保存 printf() 函数的结果,在您的情况下为 11 + 1 (space) + 3 + 1 (\n) = 16. 所以结果是 200 乘以 1116.

您想做什么

char tempBuf[12];
ofstream myfile;
myfile.open("C:\CRC.txt");
for (i = 0; i < 200; i++, id++)
{
    sprintf(tempBuf, "%011d", id);
    myfile << tempBuf << ' ';        
    sprintf(tempBuf, "%03d", computeCrc(tempBuf));
    myFile << tempBuf << '\n';
}
myfile.close();

您正在将 sprintf()printf() 的 return 输出到文件中。 sprintf()printf() 的 return 是 int 而不是您正在创建的字符串。要输出字符串,您需要将代码更改为

for (i = 0; i < 200; i++, id++)
{
    sprintf(idstring, "%011d", id);
    myfile << idstring;
    myfile << computeCrc(idstring) << endl;
}