【发布时间】:2011-03-26 13:27:55
【问题描述】:
int item;
cin >> item;
这在我的代码中,但我希望用户能够输入整数或字符串。这基本上就是我想做的:
if(item.data_type() == string){
//stuff
}
这可能吗?
【问题讨论】:
标签: c++ types comparison
int item;
cin >> item;
这在我的代码中,但我希望用户能够输入整数或字符串。这基本上就是我想做的:
if(item.data_type() == string){
//stuff
}
这可能吗?
【问题讨论】:
标签: c++ types comparison
您不能完全做到这一点,但只要多做一些工作,您就可以做类似的事情。如果您安装了 Boost 库,则以下代码有效。它可以在没有提升的情况下完成,但是这样做很乏味。
#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;
}
}
【讨论】:
不,但你可以输入字符串,然后将其转换为整数,如果它是整数。
【讨论】:
【讨论】:
您所做的不是重视 C++ 代码。它不会编译!
你的问题是:
这在我的代码中,但我希望用户能够输入整数或字符串
然后这样做:
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;
}
【讨论】: