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 r
Why reinvent the wheel? The C standard library (available in C++ as well) has a function that does exactly this:
char* p;
long converted = strtol(s, &p, 10);
if (*p) {
// conversion failed because the input wasn't a number
}
else {
// use converted
}
If you want to handle fractions or scientific notation, go with strtod
instead (you'll get a double
result).
If you want to allow hexadecimal and octal constants in C/C++ style ("0xABC"
), then make the last parameter 0
instead.
Your function then can be written as
bool isParam(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}