Please, how do I test for data types in C++, for instance if am expecting an input from a user and I want to check if the user enter an int, a double, a char or a boolean.
Asked
Active
Viewed 142 times
0
-
4What's `5` ? int or char? or double? – Alex K. Jul 21 '15 at 16:29
-
This might help, too: http://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c – RhinoDevel Jul 21 '15 at 16:29
-
If you read the input into a `std::string`, you can test each type with [`boost::conversion::try_lexical_convert`](http://www.boost.org/doc/libs/1_58_0/doc/html/boost_lexical_cast/synopsis.html). – Drew Dormann Jul 21 '15 at 16:40
1 Answers
0
You read the input into a string (std::getline()
), then attempt to parse it. strtod()
checking if it parses as a double (via the end pointer). If that fails, strtol()
to check if it parses as an int. I assume you mean "true" / "false" for the bool so you'd do a string ==
on those. And if all that fails, use it as a verbatim string.
All that is highly fragile, of course. The user might enter decimal commas or decimal points. He might add a whitespace after "true". All that stuff...
If you are looking for real parsing, Boost.Spirit would be the place to look for, but that is very involved and more for production-level parsers so I doubt that is what you are looking for.

DevSolar
- 67,862
- 21
- 134
- 209
-
Yaaa, you are right I was actually looking for something simpler, just like in PHP where you can use var_dump() to get the data type of a variable. – Bhekor Jul 21 '15 at 16:47
-
Unfortunately plain old data types in C++ are just raw bytes of memory. No meta information. – cppguy Jul 21 '15 at 17:05