【问题标题】:How do I validate int input using std::stoi() in C++?如何在 C++ 中使用 std::stoi() 验证 int 输入?
【发布时间】:2016-10-13 21:46:48
【问题描述】:

有没有办法在 C++ 中使用 std::stoi() 检查字符串输入是否可转换为 int? (例如,我是否可以检查是否会引发 invalid_argument 异常?)

一个不起作用的例子,但希望能解释我正在尝试做的事情:

    string response;
    cout << prompt;

    if (std::stoi(response) throws invalid_argument) { //Something like this
        return std::stoi(response);
    }
    else {
        badInput = true;
        cout << "Invalid input. Please try again!\n";
    }

研究:
我找到了几种检查字符串是否为 int 的方法,但我希望有一种方法可以使用我还没有找到的 std::stoi()

【问题讨论】:

  • response的类型是什么?您能否提供一个完整的示例,以便我们自己检查? stackoverflow.com/help/mcve
  • 更新澄清
  • 我已阅读文档。
  • "如何检查是否会抛出 invalid_argument 异常?"为什么不直接catch 抛出 的异常,而不是尝试预测和避免它?您不能使用stoi 来检查stoi 是否会抛出异常,而不会抛出异常......当然。

标签: c++ string validation int


【解决方案1】:

你应该在抛出异常时捕获它,而不是试图预先确定它是否会被抛出。

string response; 
cin >> response;

try {
    return std::stoi(response);
}
catch (...) {
    badInput = true;
    cout << "Invalid input. Please try again!\n";
}

【讨论】:

    【解决方案2】:

    std::stoi() 如果无法执行转换,则会引发异常。 查看此 c++ 文档中的“异常”部分 http://www.cplusplus.com/reference/string/stoi/

    【讨论】:

      【解决方案3】:

      std::stoi 尽可能多地转换,只有在没有要转换的情况下才会抛出异常。但是,std::stoi 接受一个表示起始索引的指针参数,该参数更新为终止转换的字符。 See MSDN stoi docs here.

      可以使用stoi进行测试,传入0作为起始索引,然后验证返回的索引是否与字符串的总长度一致。

      将以下内容视为伪代码,它应该让您了解如何使其工作,假设响应是 std::string:

      std::size_t index = 0;
      auto result = std::stoi(response, &index);
      if(index == response.length()){
          // successful conversion
          return result;
      }
      else{
          // something in the string stopped the conversion, at index
      }
      

      【讨论】:

      • “您可以使用 stoi 通过传递 0 作为起始索引来进行测试” - 您不会将任何内容作为“起始索引”传递。第一个未转换字符(或字符串结尾)的索引存储在您提供的指针中。函数不会检查该指针预先指向的内容。
      猜你喜欢
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      相关资源
      最近更新 更多