我想從字符串中獲取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)
回覆加強異常處理 – RvdK