处理错误一般都比较费劲。你的想法是可以的,先读到一个char数组里,然后再用 strtod 转。
我只写个读数的程序,比如:
程序代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double x;
char buf[31], *endptr;
while (scanf(" %30[^\n]", buf) == 1) {
x = strtod(buf, &endptr);
if (endptr == buf)
fprintf(stderr,
"Convertion failed: Can't convert `%s\' to a double!\n",
buf);
else if (*endptr != '\0')
fprintf(stderr,
"Convertion failed: `%s\' was converted to %lg, "
"and the rest `%s\' is discarded.\n",
buf, x, endptr);
else
fprintf(stdout,
"Convertion succeeded: `%s\' was converted to %lg\n",
buf, x);
}
return 0;
}
运行的结果可能是这样:
12.34 # 合理的数可以合理的转换。
Convertion succeeded: `12.34' was converted to 12.34
abc # 不是数的肯定不行。
Convertion failed: Can't convert `abc' to a double!
12.34abc # 有点"像"数的能转的部分转,不能换的部分提示出来。
Convertion failed: `12.34abc' was converted to 12.34, and the rest `abc' is discarded.
1abc.234 # 同上
Convertion failed: `1abc.234' was converted to 1, and the rest `abc.234' is discarded.
12.34 23.45 # 不同时转两个数。
Convertion failed: `12.34 23.45' was converted to 12.34, and the rest ` 23.45' is discarded.
12e34 # 如果数里含的字母是有意义的,可以正确换转。
Convertion succeeded: `12e34' was converted to 1.2e+35