Writing CRC data to .txt file

723 views Asked by At

This seems like it should be a basic C++ process, but I'm not familiar with the data output.

When I print the data without outputting to a text file, I get the correct values.

example: 00150017000 181

When printing to a text file, this is what I get:

11161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116

Here is my code:

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();

Everything else works fine and I know the CRC is generated correctly. Just a matter of getting the correct output.

I was able to output the console screen to a text file by adding "> CRC.txt" to the Debugging Properties Command Arguments, but I just wanted to know how I could incorporate the ofstream method into this.

Thanks in advance.

2

There are 2 answers

4
rozina On BEST ANSWER

You don't save to the file what you think you save. First you save the result of sprintf() function, which in your case is 11. Then you save the result of the printf() function which in your case is 11 + 1 (space) + 3 + 1 (\n) = 16. So the result is 200 times 1116.

What you wanted to do

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();
0
NathanOliver On

You are ouputing the return of sprintf() and printf() to the file. The returns of sprintf() and printf() are int and not the string you are creating. To output the string you need to change your code to

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