【发布时间】:2016-01-25 10:05:45
【问题描述】:
我想从字符串中获取 int,而不是直接使用 int 类型从 getline() 中获取优势,但是如果输入不是实际的 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)
【问题讨论】:
-
阅读异常处理