method to check if char array is a number ?

suppose char array being "-123.456" then the method confirms it is a number, and if the array is "45fg" then the method confirms it is not a number, is there a method to do this ??
Last edited on
closed account (E0p9LyTq)
As far as I know there is no one means in the C library to determine of a C-string contains a number because of the sign and decimal point.

I'd write a function to check each element if it were a '+', '-' or '.' and then check the element isdigit(). If any element should fail either test then the C-string contains something other than a 'pure' number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>

bool is_double( const std::string& str )
{
    std::size_t pos ;
    try
    {
        // http://en.cppreference.com/w/cpp/string/basic_string/stof        
        std::stod( str, std::addressof(pos) ) ;
        return pos == str.size() ; // entire string has been consumed
    }
    catch( const std::exception& ) { return false ; } // no conversion or out of range of double
}

int main()
{
    for( std::string str : { "-123.456",  "45fg", "1.0e-234", "inf", "nan", "", "0xab.cdP+55", "1.e+1234" } )
    std::cout << '"' << str << "\" ? " << std::boolalpha << is_double(str) << '\n' ;
}

http://coliru.stacked-crooked.com/a/46e59d9266207ce9

Pure C: http://en.cppreference.com/w/c/string/byte/strtof
Last edited on
Topic archived. No new replies allowed.