C++ string to double conversion

TimeCoder picture TimeCoder · Jan 21, 2011 · Viewed 220.9k times · Source

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

Answer

0x77D picture 0x77D · Jan 21, 2011

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