14

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

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

另一个编辑:

我正在 gcc 中运行这个

#include <stdio.h>
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 并且没有包含正确的标题。

4

3 回答 3

31

You are missing an include : #include <stdlib.h>, so GCC creates an implicit declaration of atof and atod, leading to garbage values.

And the format specifier for double is %f, not %d (that is for integers).

#include <stdlib.h>
#include <stdio.h>

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
于 2012-05-15T17:40:52.333 回答
1

您发布的代码是正确的,应该可以工作。但请检查您在char*. 如果正确的值太大而无法表示,函数将返回正值或负值HUGE_VAL。检查您在计算机上的char*最大值floatdouble可以表示的最大值。

检查此页面以供strtod参考,并检查此页面以atof参考

我已经尝试过您在 Windows 和 Linux 中提供的示例,并且效果很好。

于 2012-05-15T17:26:54.913 回答
0
printf("price: %d, %f",temp,ftemp); 
              ^^^

这是你的问题。由于参数是 typedoublefloat,因此您应该同时使用%f两者(因为printf是可变参数函数,ftemp将被提升为double)。

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

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

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

两者都用%f

于 2012-05-15T17:51:59.763 回答