将char *转换为float或double

我有一个从文件读入的值,并存储为char *。 值是货币编号,#。##,##。##或###。##。 我想将char *转换为我可以在计算中使用的数字,我尝试过atof和strtod,他们只是给我垃圾数字。 这样做的正确方法是什么,为什么我做错的方式呢?

这基本上就是我正在做的事情,只是从文件读入char *值。 当我打印出temp和ftemp变量时,它们只是垃圾,巨大的负数。

另一个编辑:

我在gcc中运行这个

#include  int main() { char *test = "12.11"; double temp = strtod(test,NULL); float ftemp = atof(test); printf("price: %f, %f",temp,ftemp); return 0; 

}

我的输出是价格:3344336.000000,3344336.000000

编辑:这是我的代码

 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); 

我的输入文件是非常简单的名称,值对如下:

 NAME|VALUE NAME|VALUE NAME|VALUE 

价值是美元金额

已解决:谢谢大家,我使用%d而不是%f,并且没有包含正确的标题。

你缺少一个include: #include ,所以GCC创建一个atofatod的隐式声明,导致垃圾值。

double的格式说明符是%f ,而不是%d (即整数)。

 #include  #include  int main() { char *test = "12.11"; double temp = strtod(test,NULL); float ftemp = atof(test); printf("price: %f, %f",temp,ftemp); return 0; } /* Output */ price: 12.110000, 12.110000 

您发布的代码是正确的,应该有效。 但要确切查看char* 。 如果要表示的值正确,则函数将返回正或负HUGE_VAL 。 检查char*中的内容,以及floatdouble在计算机上可以表示的最大值。

请查看此页面以获取strtod参考和此页面以供参考 。

我已经尝试过您在Windows和Linux中提供的示例,但它运行良好。

 printf("price: %d, %f",temp,ftemp); ^^^ 

这是你的问题。 由于参数是doublefloat类型,因此你应该使用%f (因为printf是一个可变参数函数, ftemp将被提升为double )。

%d期望相应的参数是int类型,而不是double

printf这样的变量printf并不真正知道变量参数列表中参数的类型。 你必须用转换说明符告诉它。 由于你告诉printf第一个参数应该是一个int ,printf将从参数列表中获取下一个sizeof (int)字节并将其解释为整数值; 因此第一个垃圾号码。

现在,几乎可以保证sizeof (int) < sizeof (double) ,所以当printf从参数列表中获取下一个sizeof (double)字节时,它可能从temp的中间字节开始,而不是ftemp的第一个字节; 因此第二个垃圾号码。

两者都使用%f