简体   繁体   中英

C++ stod function equivalent

A friend of mine sent me his program. He uses "stod" function to convert string to double. Is there any other possibility to do such thing?

My complier shows error "stod was not declared in this scope"

I've included #include <string> #include <cstdlib> but nothing has changed.

My complier doesn't use C++11 features. By the way, that program were prepared as a school project, without purpose of using C++11.

std::atof() is a quick option handed over from C language, you have to include <cstdlib> 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 a 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 check needed to validate correct conversion

EDIT: You will need to test the stringstream for failure with

if (ss.fail()) { /* error */ }

Source http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM