尝试从字符串

时间:2016-01-25 10:05:46

标签: c++ string int

我想从字符串中获取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)

1 个答案:

答案 0 :(得分: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;
}