Is their any fuction available in C++ that can determine that a string
contains a numeric value.
The value cabn be in hex, int, float. i.e. "1256" , "123.566" ,
"0xffff"
Thnx
AFAIK, there is no *single* function that can recognize a numeric
string in any format. You can go one of two ways here: you can use a
combination of standard library functions (strtol(), strtod(),
strchr(), etc.) to attempt to convert the string to a numeric value,
and then check for any unconverted characters. The general algorithm
would be:
Strip leading whitespace
If the first character is '0' then
If the second character is 'x' or 'X' then
Convert the string using strtol(string, &check, 16)
where check is a pointer to a character
If *check is 0 or whitespace then
the string is an integer in hex format
Else
the string is not numeric
Else
Convert the string using strtol(string, &check, 8)
If *check is 0 or whitespace
the string is an integer in octal format
Else
the string is not numeric
End If
Else
If strpbrk(string, ".eE") is not null then
Convert the string using strtod(string, &check)
If *check is whitespace or 0 then
the string is a float in decimal
Else
the string is not numeric
End If
Else
Convert the string using strtol(string, &check, 10)
If *check is whitespace or 0 then
the string is an integer in decimal
Else
the string is not numeric
End If
End If
End If
Alternately, you can build a finite state machine that will scan the
string character by character; if the machine is in an accepting state
after scanning the whole string, then the string is numeric. This
isn't as straightforward a method as the above, and it can involve
quite a bit more work. The tradeoff is that you can accept strings in
any format you like, such as "1,234,567", where the method above
won't.
FSMs can get *very* tedious to write if you have a lot of states.
There are tools like lex or flex that will generate FSMs based on
rules you specify, but they take a little time to learn, and they're
not universally available. However, if you decide to expand your
rules for a valid numeric string, it's a helluva lot easier to edit
the specification file for lex than to try to edit the FSM code
itself.