Hi guys,
How do I say if something "is a number"
ie)
PSEUDO CODE
IF X is a number THEN
.....
ELSE
etc.
Thanks
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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 }