Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 360
Paul R. Avatar asked Feb 03 '26 07:02

Paul R.


1 Answers

You might want to use std::stod:

[live]

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);
    if (b)
      std::cout << d;
    else
      std::cout << "Wrong input";
}

[edit]

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.

like image 116
marcinj Avatar answered Feb 05 '26 20:02

marcinj