1

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Khabbab Zakaria
  • 383
  • 3
  • 6
  • 19

2 Answers2

0

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.

Ruben
  • 71
  • 1
  • 5
  • @Yunnosch Thanks for the insightful comment. I was basing my assumption off of the assignment of the variable, but I can see that there could be underlying issues, like the variable being set to int before assignment. Again, thanks for the insightful comment, as I'm new to answering questions, I have lots to learn. – Ruben May 25 '21 at 10:34
0

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

Zig Razor
  • 3,381
  • 2
  • 15
  • 35