Is there a stl or boost function to determine if a string is numeric?

No, there's not a ready-made way to do this directly.

You could use boost::lexical_cast<double>(your_string) or std::stod(your_string) and if it throws an exception then your string is not a double.

C++11:

    bool is_a_number = false;
    try
    {
        std::stod(your_string);
        is_a_number = true;
    }
    catch(const std::exception &)
    {
        // if it throws, it's not a number.
    }

Boost:

    bool is_a_number = false;
    try
    {
        lexical_cast<double>(your_string);
        is_a_number = true;
    }
    catch(bad_lexical_cast &)
    {
        // if it throws, it's not a number.
    }

boost::regex (or std::regex, if you have C++0x) can be used; you can defined what you want to accept (e.g. in your context, is "0x12E" a number or not?). For C++ integers:

"\\s*[+-]?([1-9][0-9]*|0[0-7]*|0[xX][0-9a-fA-F]+)"

For C++ floating point:

"\\s*[+-]?([0-9]+\\.[0-9]*([Ee][+-]?[0-9]+)?|\\.[0-9]+([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)"

But depending on what you're doing, you might not need to support things that complex. The two examples you cite would be covered by

"[0-9]+(\\.[0-9]*)?"

for example.

If you're going to need the numeric value later, it may also be just as easy to convert the string into an istringstream, and do the convertion immediately. If there's no error, and you extract all of the characters, the string was a number; if not, it wasn't. This will give you less control over the exact format you want to accept, however.

Tags:

C++

Stl

Boost