I have a value that I am reading from a file and stored as char *. The value is a monetary number, #. ##, ##. ## or ###. ##. I want to convert char * to a number that I can use in calculations, I tried atof and strtod and they just give me the garbage numbers. What is the right way to do this, and why am I doing it wrong?
This is essentially what I am doing, only the char * value is read from the file. When I print the variables temp and ftemp, they are just garbage, giant negative numbers.
Other Edit:
I do exactly that in gcc
#include <stdio.h> int main() { char *test = "12.11"; double temp = strtod(test,NULL); float ftemp = atof(test); printf("price: %f, %f",temp,ftemp); return 0;
}
and my result is the price: 3344336.000000, 3344336.000000
Edit: Here is my code
if(file != NULL) { char curLine [128]; while(fgets(curLine, sizeof curLine, file) != NULL) { tempVal = strtok(curLine,"|"); pairs[i].name= strdup(tempVal); tempVal = strtok(NULL,"|"); pairs[i].value= strdup(tempVal); ++i; } fclose(file); } double temp = strtod(pairs[0].value,NULL); float ftemp = atof(pairs[0].value); printf("price: %d, %f",temp,ftemp);
my input file is a very simple name, pairs of values, such as:
NAME|VALUE NAME|VALUE NAME|VALUE
with a value of dollar amounts
SOLVED: Thanks to everyone, I used% d instead of% f and did not have the correct headers.
Andrew
source share