Hi guys,
How do I say if something "is a number"
ie)
PSEUDO CODE
IF X is a number THEN
.....
ELSE
etc.
Thanks
Printable View
Hi guys,
How do I say if something "is a number"
ie)
PSEUDO CODE
IF X is a number THEN
.....
ELSE
etc.
Thanks
You can't do that in C & C++.
You can either check if the input was done correctly, e.g. in C++ you would do:
Or you read the data in as a string (which will accept ANYTHING) using for example getline(cin, str), and then try to convert the input to a number.Code:int x;
if (cin >> x)
{
.. x is a number...
}
else
{
.. input was not valid, either x is not a number, or something else
didn't allow a valid value to be read - e.g. end of file.
}
--
Mats
Thanks :)
So, with the string. How am I going to check that it is not a value?
There are several variants (and you should of course still check that the input itself was OK - otherwise you may end up processing the old data from last successful operation, potentially FOREVER, if there is nothing else stopping the program).
So, the most C++ style thing is to use stringstream, which is like cin/cout and such, except it does the "in" and "out" in form of a string. So something like this:
Code:#include <sstream>
... in some function ...
std::string str = "1234";
std::stringstream ss;
int x;
ss << str;
if (ss >> x)
... str was a number.
If you want to check that there are no non-numeric characters following the number, modify matsp's example to:
Code:std::stringstream ss(str);
int x;
if (ss >> x && ss.eof())
// ... str was a number.
There is also boost::lexical_cast. But it throws in case of error:
boost::lexical_cast can pretty much convert anything to anything. It can also be extended with custom data types if the custom data types provide the correct interface (read: they are done correctly).Code:try
{
int x = boost::lexical_cast<int>(str);
}
catch(const boost::bad_lexical_cast&)
{
// str is not an integer
}