I am trying to read type double
values from a char buffer
word by word. In the file I have some values like 0.032 0.1234 8e-6 4e-3
etc. Here is my code which is using atof()
function to convert word (stored in array 's
') to a double value num
:
char s[50];
double num;
while(getline(str, line))
{
int i=0, j=0;
while(line[i] != '\0')
{
if(line[i] != ' ')
{
s[j] = line[i];
//cout << s[j]; <-- output of s[j] shows correct values (reading 'e' correctly)
j++;
}
else
{
num = atof(s);
cout << num << " ";
j=0;
}
i++;
}
cout << endl;
}
Whenever numbers which include 'e' in them (like 8e-6) comes, atof() function just returns 0 for them. Output for above example values comes out to be 0.032 0.1234 0 0
.
I tried to check with a demo array and there atof() worked fine.
char t[10];
t[0] = '8';
t[1] = 'e';
t[2] = '-';
t[3] = '5';
t[4] = '\0';
double td = atof(t);
cout << "td = " << td << endl;
Here the output is td = 8e-05
I have included both <stdio.h>
and <stdlib.h>
. Any idea why it's not working?