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 come from 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 ?
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With