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 error 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, is there anything like that in C to directly convert a float to a string?
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);