Here is a way of doing it using string streams (btw, you probably want to convert a std::string
to a double
, not a single char
, since you lose precision in the latter case):
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string str;
std::stringstream ss;
std::getline(std::cin, str); // read the string
ss << str; // send it to the string stream
double x;
if(ss >> x) // send it to a double, test for correctness
{
std::cout << "success, " << " x = " << x << std::endl;
}
else
{
std::cout << "error converting " << str << std::endl;
}
}
Or, if your compiler is C++11 compliant, you can use the std::stod function, that converts a std::string
into a double
, like
double x = std::stod(str);
The latter does basically what the first code snippet does, but it throws an std::invalid_argument
exception in case it fails the conversion.