2011-03-26 81 views
2
int item; 
cin >> item; 

这是在我的代码中,但我希望用户能够输入整数或字符串。这基本上就是我想做的事:比较数据类型

if(item.data_type() == string){ 
    //stuff 
} 

这可能吗?

回答

1

不,但你可以输入字符串,然后将其转换为整数,如果它是整数。

+0

这就是我一直在寻找的东西 - 我该怎么做? – pighead10 2011-03-26 13:58:53

2

你不能做到这些,但有一点更多的工作可以做类似的事情。如果您安装了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; 
    } 
} 
0

你在做什么不是价值的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; 
} 
+0

我已经安装了boost,但我不想将它用于在命令中运行的这个小型RPG。 – pighead10 2011-03-26 13:59:23