本文介绍了转换的char *浮动或双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的价值从文件中读取并存储为一个char *。该值是一个货币数,###,##,##,或###。##。我想为char *转换为数字我可以在计算中使用,我已经试过ATOF和关于strtod,他们只是给我的垃圾数量。什么是做到这一点的正确方法,为什么就是这样,我做错了?

I have a value I read in from a file and is stored as a char*. The value is a monetary number, #.##, ##.##, or ###.##. I want to convert the char* to a number I can use in calculations, I've tried atof and strtod and they just give me garbage numbers. What is the correct way to do this, and why is the way I am doing it wrong?

这基本上是我在做什么,只是字符*值从一个文件读入。当我打印出来的温度和ftemp变量他们只是垃圾,巨大的负数。

This is essentially what I am doing, just the char* value is read in from a file. When I print out the temp and ftemp variables they are just garbage, gigantic negative numbers.

另一个编辑:

我正是在这个海湾合作委员会运行

I am running exactly this in 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

and my output is price: 3344336.000000, 3344336.000000

编辑:这是我的code

Here is my code

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

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

my input file is very simple name, value pairs like this:

NAME|VALUE
NAME|VALUE
NAME|VALUE

与值是美元金额

解决:谢谢大家,我是用%d个代替%F,并没有正确的头文件包含

SOLVED: Thank you all, I was using %d instead of %f and didn't have the right headers included.

推荐答案

您缺少一个包括:
的#include&LT;文件stdlib.h&GT; ,所以GCC创建的隐式声明ATOF atod ,导致垃圾值。

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

和格式说明双是%F ,而不是%d个(即整数)。

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

这篇关于转换的char *浮动或双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:44