在C ++中将一串数字转换为double

时间:2015-07-25 13:37:35

标签: c++ string floating-point double

这里我试图将一串数字转换成相应的双数字。

double string_to_double ( const char* str)
{

int i = 0;
double* num = (double *)malloc(sizeof(double));
*num = 0;
int fract_fact = 10;
int size = strlen(str);

if ( str[0] != '.')  // if its not starting with a point then take out the first decimal digit and place it in the number instead of 0.

  *num = (str[i] - '0');


for ( i = 1; i < size; ++i){

    if ( str[i] == '.'){

        i++;

        for (int j = i; j < size; ++j){ // after encountering point the rest of the part is fractional.


            *num += (str[j] - '0') / fract_fact; // summing up the next fractional digit.
            fract_fact *= 10; // increasing the farct_fact by a factor of 10 so that next fractional digit can be added rightly.
        }

        break;
    }

    *num = *num * 10 + ( str[i] - '0');
}

return *num;
}

当我从主要

中将其称为以下内容时
cout << string_to_double("123.22");

它的输出是

  

123

但为什么呢?我做错了什么?

2 个答案:

答案 0 :(得分:5)

*num += (str[j] - '0') / fract_fact;

应该是

*num += (str[j] - '0') / (double)fract_fact;

您的版本执行整数运算,总是计算为零。

不是你问的问题,但为什么要分配num?

double num;

num = ...

return num;

更简单,它不会泄漏记忆。

答案 1 :(得分:0)

您可以非常轻松地使用标准功能处理此问题。

std::size_t end = 0;
std::string string_number = "123.456";
double number = stod(string_number, &end);
if (end == string_number.size())
    std::cout << "the number is " << number;
else
    std::cout << "error in conversion";