Converting string to integer, double, float without having to catch exceptions

Use a std::stringstream and capture the result of operator>>().

For example:

#include <string>
#include <iostream>
#include <sstream>

int main(int, char*[])
{
    std::stringstream sstr1("12345");
    std::stringstream sstr2("foo");

    int i1(0);
    int i2(0);

    //C++98
    bool success1 = sstr1 >> i1;
    //C++11 (previous is forbidden in c++11)
    success1 = sstr1.good();

    //C++98
    bool success2 = sstr2 >> i2;
    //C++11 (previous is forbidden in c++11)
    success2 = sstr2.good();

    std::cout << "i1=" << i1 << " success=" << success1 << std::endl;
    std::cout << "i2=" << i2 << " success=" << success2 << std::endl;

    return 0;
}

Prints:

i1=12345 success=1
i2=0 success=0

Note, this is basically what boost::lexical_cast does, except that boost::lexical_cast throws a boost::bad_lexical_cast exception on failure instead of using a return code.

See: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html

For std::stringstream::good, see: http://www.cplusplus.com/reference/ios/ios/good/


To avoid exceptions, go back to a time when exceptions didn't exist. These functions were carried over from C but they're still useful today: strtod and strtol. (There's also a strtof but doubles will auto-convert to float anyway). You check for errors by seeing if the decoding reached the end of the string, as indicated by a zero character value.

char * pEnd = NULL;
double d = strtod(str.c_str(), &pEnd);
if (*pEnd) // error was detected

Tags:

C++

Exception