59

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

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
TimeCoder
  • 1,379
  • 3
  • 12
  • 13
  • possible duplicate of [String in scientific notation C++ to double conversion](http://stackoverflow.com/questions/1710447/string-in-scientific-notation-c-to-double-conversion) – David Rodríguez - dribeas Jan 20 '11 at 23:53
  • This is basically a duplicate with the only difference that you do not even need to go through the string stage, as you can read directly into the double. – David Rodríguez - dribeas Jan 20 '11 at 23:54
  • 3
    When you convert a `char` to an `int`, you're getting the code ofthe character, not its perceived "value". In other words, `int x = '0';` sets `x` to `48` (if you're in an ASCII-compatible locale), not `0`. – Mike DeSimone Jan 20 '11 at 23:56
  • possible duplicate of [How do I convert a double into a string in C++?](http://stackoverflow.com/questions/332111/how-do-i-convert-a-double-into-a-string-in-c) – jb. May 22 '14 at 16:21
  • 1
    Not a duplicate of that. Seriously @jb., once again `String`->`Double` is not the same as `Double`->`String`. – JasonMArcher May 22 '14 at 17:35

7 Answers7

83
#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999 (which is double, whitespace was automatically stripped)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double

As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long

Bad
  • 4,967
  • 4
  • 34
  • 50
82

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;
}
0x77D
  • 1,564
  • 2
  • 18
  • 17
17

The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.

To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:

double lol;
openfile >> lol;

This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:

double lol;
openfile >> lol;

if (openfile.fail()) {
    cout << "Couldn't read a double from the file." << endl;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 2
    If you're not reading from a stream, you need to use a function to perform the conversion, such as `atof()` from ``. – Mike DeSimone Jan 21 '11 at 00:00
  • 5
    @Mike: As a beginner, when you're not reading from a stream, but have a string, you need to put it into a stringstream and read from that. – sbi Jan 21 '11 at 00:02
5

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}
MatiasFG
  • 576
  • 2
  • 8
1

The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.

Compile and run this program, then study it. It is simple

#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;

int main()
{
    // Converting the content of a char array or a string to a double variable
    double d;
    string S;
    S = "4.5";
    istringstream(S) >> d;    
    cout << "\nThe value of the double variable d is " << d << endl;
    istringstream("9.87654") >> d;  
    cout << "\nNow the value of the double variable d is " << d << endl;



    // Converting a double to string with formatting restrictions
    double D=3.771234567;

    ostringstream Q;
    Q.fill('#');
    Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
    S = Q.str(); // formatted converted double is now in string 

    cout << "\nThe value of the string variable S is " << S << endl;
    return 0;
}

Prof. Martinez

  • Refer to system/compiler header files with `<` and `>` as they are such files. Otherwise, the compiler will look up first on the local compile directories and also on include directories set by the `-I` flag. – ranu May 27 '20 at 17:48
0

Coversion from string to double can be achieved by using the 'strtod()' function from the library 'stdlib.h'

#include <iostream>
#include <stdlib.h>
int main () 
{
    std::string data="20.9";
    double value = strtod(data.c_str(), NULL);
    std::cout<<value<<'\n';
    return 0;
}
EleetGeek
  • 121
  • 1
  • 5
  • 1
    In C++ there's a typed null value called `nullptr` that came with the C++11 standard. – ranu May 27 '20 at 17:48
-4
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}

or

//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]- (s[x]<='9' ? '0':'0'+7)   ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}
  • 1
    This doesn't compile and is very difficult to read, doesn't use existent features of the standard library. Also, the question is 2 years old and has been answered already. – unkulunkulu Apr 17 '13 at 11:17
  • 1
    This does compile. Btw, i thought i'd provide an algorithm as opposed to the other answers. – ausercomment Apr 17 '13 at 11:36
  • 1
    The reason you couldn't compile it was that arg1 in _string_to_double, was not specified to be of namespace std. It is fixed now. – ausercomment Apr 17 '13 at 11:44
  • 1
    The other problems still remain: no indentation, unclear flow, completely inconsistent spacing, name starting with an underscore. I'm not confident in this algorithm. And this was not an algorithm question. – unkulunkulu Apr 17 '13 at 11:47
  • 3
    This is not a view on life discussion. In fact, this is is not a discussion at all, you're being told by a more experienced user of this site what kinds of answers are more welcome here, that's simply it. Few will try and dig through code, author of which made no effort to make it readable. – unkulunkulu Apr 17 '13 at 12:16