Hi
How can I check if a value is numeric or not?
for example:
user pass some values in main program via command line,all these parameters must be numeric,so I have to make sure that value is numeric or not.
I did not find any function for this checking.
#include <sstream>
#include <string>
double string2double( const std::string& a )
{
// Convert a string representation of a number into a floating point value.
// Throws an int if the string contains anything but whitespace and a valid
// numeric representation.
//
double result;
std::string s( a );
// Get rid of any trailing whitespace
s.erase( s.find_last_not_of( " \f\n\r\t\v" ) + 1 );
// Read it into the target type
std::istringstream ss( s );
ss >> result;
// Check to see that there is nothing left over
if (!ss.eof())
throw 1;
return result;
}
You can use this with your command-line arguments...
I like Duoas' function. I would make that a template so it converts to int, double, float, etc. and I would change the parameter: std::string a. This way the function receives a copy of the string and line 11 becomes unnecessary.
The template is unnecessary -- a double will automatically convert to an int.
However, changing the argument type will break it, as it needs to have the const char* to string capability, and the generated strings are temporaries.
try to go through each digit of the text entered and used the isdigit() function (in the cctype header) as creativemfs pointed out. something like this should work fine
1 2 3 4 5 6 7 8 9
char stuff[10];
cin.getline(stuff, 10, '\n');
for (int i = 0; i < strlen(stuff); i++)
{
if (isdigit(stuff[i])
continue;
elsereturnfalse;
}
@ne555
You cannot hack out pieces of an algorithm and expect it to work properly.
Line 21 will fail if line 14 is missing -- even if the user only gives the string "42 " as input.
The algorithm assumes the following:
7 8
// Throws an int if the string contains anything but whitespace and a valid
// numeric representation.
That is, the string must contain a valid number, and may also have leading and trailing whitespace. If it contains anything else, it fails.
If you change the algorithm then its behavior will also change.
@ascii
"-2.3" is a number. (And ".4.9-7" is not.) Likewise, "6.02e23" is a number.
Duoas, I presume you are an engineer? I see you quoting the Avogadro constant there, although not very precise, hehe. 6.022045e23 is how I remember it. :-)
damn i just got pwned. in one of my more recent programs which i was basing my code off of it had support for a - symbol so negatives werent a problem, but its true that scientific notation wouldnt be recognized. anyhow 6.02e23 would be far too large to for an int wouldnt it?
yeah i realize that, but generally someone will write out 4000 not 4e3. when you get to the point that you need to be using scientific notation youll probably be dealing with numbers out of the range of an int.