2011-03-26 147 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