I have a string of class string
string str;
how can I check if it is a number or not, str can only have 3 possible types described below like
abcd
or a number like
123.4
or a number with a parenthesis attach to the end it for example
456)
note the parenthesis at the end of “str” is the only possible combination of number and none number
where the bottom two are considered valid numbers, I know I could use lexical_cast if only the first 2 cases occur, but how about considering all 3 possible cases to occur?
I don’t need to do anything fancy with str, I just need to know whether it is a valid number as I described
The C++ solution for parsing strings manually is string streams. Put your string into a
std::istringstreamand read from that.What you could do to parse this is to try to read an (
unsigned)intfrom the string.If this fails, it is a string not starting with digits.
If it works, peek at the next character. If that’s a
.you have a floating point number, if it’s a), you have an integer number. (Otherwise you have a reading error.)Something along the lines of
Does this make sense?