2016-01-25 57 views
3

我想從字符串中獲取int,而不是直接使用int類型來從getline()中獲得優勢,但是某種程度上,如果輸入不是實際的int 。嘗試從字符串獲取int時出錯

#include <iostream> 
#include <string> 

using namespace std; 

int main (int argc, char** argv) 
{ 
    string word = {0}; 

    cout << "Enter the number 5 : "; 

    getline(cin, word); 

    int i_word = stoi(word); 

    cout << "Your answer : " << i_word << endl; 

    return 0; 
} 

當用戶輸入爲5(或任何其它INT)的輸出爲:

Enter the number 5 : 5 
Your answer : 5 

當用戶輸入或者是ENTER或任何其他字母,單詞,等...:

Enter the number 5 : e 
terminate called after throwing an instance of 'std::invalid_argument' 
    what(): stoi 
Abandon (core dumped) 
+4

回覆加強異常處理 – RvdK

回答

4

這就是所謂的異常處理:

try 
{ 
    int i_word = stoi(word); 

    cout << "Your answer : " << i_word << endl; 
} 
catch (const std::invalid_argument& e) 
{ 
    cout << "Invalid answer : " << word << endl; 
} 
catch (const std::out_of_range& e) 
{ 
    cout << "Invalid answer : " << word << endl; 
} 
+0

整潔,正是我所需要的。我不知道在C++中有異常處理mecanism,我試圖自己學習。非常感謝您的快速和明確的答案。 –

+0

@Gradiuss也許從書中學習會是更好的選擇。 – user2079303

+0

這就是我的想法,但現在我正在測試什麼最適合C和C++,但我發現C++方便易學。但感謝您的意見@ user2079303 –

相關問題