已编辑以增加价值调用errno == ERANGE;,下面用于说明
首先,您在帖子中表示您尝试过:
char * num1 = "12.2";
double numD1 = atof(num1);
这应该有效。
最简单的方法是:(你已经试过了)
double x = atof("12.2");
atof()- 将字符串的初始部分转换为双精度表示。
更好的是:
double x = strtod("12.3", &ptr);
strtod():
C 库函数double strtod(const char *str, char **endptr)
将参数 str 指向的字符串转换为浮点数
号码(类型double)。如果endptr 不是NULL,则指向
转换中使用的最后一个字符之后的字符存储在
endptr 引用的位置。如果strtod() 无法转换字符串,因为正确的值超出了可表示值的范围,则它将errno 设置为ERANGE(在errno.h 中定义)。
这是一个使用strtod(); 和两个输入的示例:(也说明了errno 的使用)
#include <errno.h>
int main ()
{
char input[] = "10.0 5.0";
char bad1[] = "0.3e500";
char bad2[] = "test";
char *ptr;
double a, b, c;
errno = 0;
a = strtod (input,&ptr);
if(errno != ERANGE)
{
errno = 0;
b = strtod (ptr,0);
if(errno != ERANGE)
{
printf ("a: %*.2lf\nb: %*.2lf\nQuotient = %*.2lf\n", 12, a, 12, b, 3, a/b);
}else printf("errno is %d\n", errno);
} else printf("errno is %d\n", errno);
//bad numeric input
errno = 0;
c = strtod (bad1, &ptr);
if(errno != ERANGE)
{
printf ("Output= %.2lf\n", c);
} else printf("errno is %d\n", errno);
//text input
errno = 0;
c = strtod (bad2, &ptr);
if(ptr != bad2)
{
printf ("Output= %.2lf\n", c);
} else printf("invalid non-numeric input: \"%s\" \n", ptr);
getchar();
return 0;
}