Paul R. Paul R. - 1 year ago 113
C++ Question

c++ atof. How to check wrong input?

So I use atof to convert my string to double. But I need to know if I get wrong input (like y564 etc.). How can I check it? I need correct number for further actions with it.

double x = atof(s.c_str());

Answer Source

You might want to use std::stod:


bool parse_double(std::string in, double& res) {
    try {
        size_t read= 0;
        res = std::stod(in, &read);
        if (in.size() != read)
            return false;
    } catch (std::invalid_argument) {
        return false;
    return true;

int main()
    double d;
    bool b = parse_double("123z", d);
    std::cout << b << ", " << d;


You may find here:

Return value

double value corresponding to the contents of str on success. If the converted value falls out of range of the return type, the return value is undefined. If no conversion can be performed, 0.0 is returned.

so that makes it impossible to decide if input is wrong or it contains 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download