9
FILE * fPointer;
float amount = 3.1415;
fPointer =fopen("vending.txt","w");
fprintf(fPointer, amount);
printf("The file has been created for the first time and we added the value %f", amount);
fclose(fPointer);

I am trying to save a float number to a text file but when I try to run this code it triggers a compiling errors because the function fprintf expects the second parameter to be an array of characters so how can I convert my float to a string so I can pass it, I have a C# background where something like .toString() is possible so is there any thing like that in C to directly cast a float to a string?

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
Fady Sadek
  • 1,091
  • 1
  • 13
  • 22

4 Answers4

9

If you can use C99 standard, then the best way is to use snprintf function. On first call you can pass it a zero-length (null) buffer and it will then return the length required to convert the floating-point value into a string. Then allocate the required memory according to what it returned and then convert safely.

This addresses the problem with sprintf that were discussed here.

Example:

int len = snprintf(NULL, 0, "%f", amount);
char *result = malloc(len + 1);
snprintf(result, len + 1, "%f", amount);
// do stuff with result
free(result);
fuz
  • 88,405
  • 25
  • 200
  • 352
Nikola Novak
  • 4,091
  • 5
  • 24
  • 33
8

The second parameter is the format string after which the format arguments follow:

fprintf(fPointer, "%f", amount);

%f tells fprintf to write this argument (amount) as string representation of the float value.

A list of possible format specifiers can (for example) be found here.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
4

By using sprintf() we can convert from float to string in c language for better understanding see the below code

#include <stdio.h>
int main()
{
   float f = 1.123456789;
   char c[50]; //size of the number
   sprintf(c, "%g", f);
   printf(c);
   printf("\n");
}

Hope this will help you.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
kumar
  • 91
  • 1
  • 10
2
// OP's code           v---- Format string expected here. 
// fprintf(fPointer, amount);

To print different text for each float, use the format string "%.*e".
FLT_DECIMAL_DIG - 1 is the number of digits needed to print each float value uniquely without undue precision.

#include <float.h>
#include <stdio.h>

fprintf(fPointer, "%.*e", FLT_DECIMAL_DIG - 1, amount);

Using "%f" will print nearly half of small float like 0.000000001f and -1.2345e-10 as 0.000000 or -0.000000.

Using "%f" will print large float like FLT_MAX with verbose text like "340282346638528859811704183484516925440.000000".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256