C ++ equivalent
A friend of mine sent me his program. It uses "stod" to convert the string to double. Is there any other way to do such a thing?
My correspondent shows an error: "Stod has not been declared in this area"
I turned #include <string> #include <cstdlib>
it on but nothing changed.
My compiler doesn't use C ++ 11 features. By the way, this program was prepared as a school project without using C ++ 11.
std::atof()
is a swift option passed from the C language, you must enable <cstdlib>
it to use it.
Otherwise, you can use std :: stringstream to handle it.
#include<sstream>
std::string value="14.5";
std::stringstream ss;
ss<< value;
double d=0.0;
ss>>d;
A quick and dirty way to convert a string to double would be
#include <sstream>
#include <string>
std::string text;
double value;
std::stringstream ss;
ss << text;
ss >> value;
But be aware of the error required to verify the correct conversion
EDIT: you will need to test the string to fail with
if (ss.fail()) { /* error */ }
Source http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/