fPrintf an integer gives weird results

354 views Asked by At

I am working on a C code where I need to do some debugging. That is why I am saving a value 'width' in a file. The codes are:

setlocale(LC_ALL, "en_US.UTF-8");
FILE* fp2;
fopen_s(&fp2, "test.txt", "w");

width = 0.05;

fprintf(fp2, " %d ", width);

fclose(fp2);

The code should print 0.05 in the file. But, it is printing -1717986918.

As I am saving the values in loop, in the file 0.05 should be saved until the loop runs, but -1717986918 is saved as the loop runs.

Can anyone help me?

width is a float variable.

2

There are 2 answers

1
Ruben On

You're trying to output width as an integer with %d, which causes this kind of behavior. If you use %f, it will work properly.

0
Zig Razor On

As you specify in comment your width variable is a float. To fprint a float you need to use %f in this way:

fprintf(fp2, " %f ", width);

For more information about formatting of fprint you can see the following reference or the wikipedia page for printf