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;
}
This function takes care of all the possible cases:
I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with
would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.
Other variations:
(only positive)
(only integer)
(only positive integer)
My solution using C++11 regex (
#include <regex>
), it can be used for more precise check, likeunsigned int
,double
etc:You can find this code at http://ideone.com/lyDtfi, this can be easily modified to meet the requirements.
Using
<regex>
. This code was tested!Try this:
The simplest I can think of in c++
Working code sample: https://ideone.com/nRX51Y