Reputation: 4305
int item;
cin >> item;
That's in my code, but I want the user to be able to type integers or strings. This is basically what I want to do:
if(item.data_type() == string){
//stuff
}
Is this possible?
Upvotes: 2
Views: 3813
Reputation: 361802
What you're doing is not value C++ code. It wouldn't compile!
Your problem is:
That's in my code, but I want the user to be able to type integers or strings
Then do this:
std::string input;
cin >> input;
int intValue;
std::string strValue;
bool isInt=false;
try
{
intValue = boost::lexical_cast<int>(input);
isInt = true;
}
catch(...) { strValue = input; }
if ( isInt)
{
//user input was int, so use intValue;
}
else
{
//user input was string, so use strValue;
}
Upvotes: 0
Reputation: 20609
You can't do exactly that, but with a little more work you can do something similar. The following code works if you have the Boost libraries installed. It can be done without boost, but its tedious to do so.
#include <boost/lexical_cast.hpp>
main() {
std::string val;
std::cout << "Value: " << std::endl;
std::cin >> val;
try {
int i = boost::lexical_cast<int>(val);
std::cout << "It's an integer: " << i << std::endl;
}
catch (boost::bad_lexical_cast &blc) {
std::cout << "It's not an integer" << std::endl;
}
}
Upvotes: 2
Reputation: 1475
Try to read this articles:
Use RTTI for Dynamic Type Identification
Upvotes: 0
Reputation: 887
no, but you can input string and then convert it to integer, if it is integer.
Upvotes: 1