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 :)
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:
or
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 adouble
, 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 adouble
, there's no meaningful conversion. Sure, you could just set thedouble
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
: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: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
Prof. Martinez
Coversion from string to double can be achieved by using the 'strtod()' function from the library 'stdlib.h'
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