【问题标题】:error while trying to get the int from a string尝试从字符串中获取 int 时出错
【发布时间】: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)

【问题讨论】:

  • 阅读异常处理

标签: c++ string int


【解决方案1】:

这叫做异常处理:

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;
}

【讨论】:

  • 整洁,正是我需要的。我不知道 C++ 中有异常处理机制,我正在尝试自己学习。非常感谢您快速清晰的回答。
  • @Gradiuss 也许从书中学习会是一个更好的选择。
  • 这就是我的想法,但现在我正在测试 C 和 C++ 之间什么最适合我,但我发现 C++ 方便且易于学习。但是感谢@user2079303的建议
  • 我更喜欢 C++:这里有很棒的教程 cplusplus.com/doc/tutorial
  • 还需要catch(std::out_of_range&amp; e)
猜你喜欢
  • 2018-04-24
  • 2014-02-03
  • 2020-06-24
  • 1970-01-01
  • 2022-01-11
  • 2020-06-20
  • 2016-10-27
  • 2021-12-04
  • 2017-03-31
相关资源
最近更新 更多