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 just wanted to throw in this idea that uses iteration but some other code does that iteration:
It's not robust like it should be when checking for a decimal point or minus sign since it allows there to be more than one of each and in any location. The good thing is that it's a single line of code and doesn't require a third-party library.
Take out the '.' and '-' if positive integers are all that are allowed.
With this solution you can check everything from negative to positive numbers and even float numbers. When you change the type of
num
to integer you will get an error if the string contains a point.Prove: C++ Program
For Validating Doubles:
}
For Validating Ints (With Negatives)
}
For Validating Unsigned Ints
}
Yet another answer, that uses
stold
(though you could also usestof
/stod
if you don't require the precision).You can do it the C++ way with boost::lexical_cast. If you really insist on not using boost you can just examine what it does and do that. It's pretty simple.
Here's another way of doing it using the
<regex>
library: