I've had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way). I wrote the below function which I believe was working smoothly (or I accidentally edited to stop it or I'm schizophrenic or Windows is schizophrenic):
bool isParam (string line)
{
if (isdigit(atoi(line.c_str())))
return true;
return false;
}
I think this regular expression should handle almost all cases
so you can try the following function that can work with both (Unicode and ANSI)
I propose a simple convention:
If conversion to ASCII is > 0 or it starts with 0 then it is a number. It is not perfect but fast.
Something like this:
Could you simply use sscanf's return code to determine if it's an int?
As it was revealed to me in an answer to my related question, I feel you should use boost::conversion::try_lexical_convert
After consulting the documentation a bit more, I came up with an answer that supports my needs, but probably won't be as helpful for others. Here it is (without the annoying return true and return false statements :-) )
The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.
Or if you want to do it the C++11 way:
As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.