我正在尝试逐字读取类型double
值。char buffer
在文件中,我有一些值,例如0.032 0.1234 8e-6 4e-3
等。这是我的代码,它使用atof()
函数将单词(存储在数组' s
'中)转换为双精度值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;
}
每当其中包含“e”的数字(如 8e-6)出现时,atof() 函数只会为它们返回 0。上述示例值的输出结果为0.032 0.1234 0 0
.
我尝试使用演示数组进行检查,并且 atof() 工作正常。
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;
这里的输出是td = 8e-05
我同时包含了<stdio.h>
和<stdlib.h>
。知道为什么它不起作用吗?