C++ string to double conversion

2019-01-11 12:48发布

Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.

I used the code(snippet)

 string word;  
 openfile >> word;
 double lol=word;

I receive the error that

Code1.cpp cannot convert `std::string' to `double' in initialization 

What does the error mean exactly? The first word is the number 50. Thanks :)

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-11 13:32

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}
查看更多
登录 后发表回答