【问题标题】:Why such loop does not catch error when inputting a string?为什么输入字符串时这样的循环不会捕获错误?
【发布时间】:2010-11-28 01:22:40
【问题描述】:
    int SelectedIndex;         
   int i = 4;
      while(SelectedIndex > i-1 || SelectedIndex < 0)
      {
       try{
       std::cout <<"please input index from 0 to " << i-1 << std::endl;
       std::cin >> SelectedIndex;
       }
       catch(std::exception& e){SelectedIndex = 999;}
      }

为什么这样的循环在输入字符串时不会捕获错误? 如何解决?我可以使用 std::string 和 Boost 库和 reg exp。

【问题讨论】:

  • 1. SelectIndex 未初始化。 2. 你能解释一下你想要发生的事情,以及实际发生的事情吗?

标签: c++ visual-studio visual-studio-2008 boost


【解决方案1】:

假设正在尝试使用std::cin 读取整数并检测用户是否输入了字符串:

如果用户确实输入了字符串,不会抛出异常(这就是您的代码无法按预期工作的原因)。相反,输入将留在缓冲区中,cin 将处于错误状态。下一个cin &gt;&gt; 将在无限循环中从缓冲区中读取相同的值,除非您在下一次迭代之前清除错误状态和缓冲区。

请参阅this article,它准确解释了如何读取整数(以及当输入字符串时会发生什么)以及如何清除错误状态和缓冲区。

【讨论】:

    【解决方案2】:

    流库默认不抛出异常。您必须先启用它,如下例所示:

    #include <iostream>
    
    int main()
    {
        int number;
        std::cin.exceptions(std::ios::failbit | std::ios::badbit | std::ios::eofbit);
        std::cout << "enter a number: ";
        try
        {
            std::cin >> number;
        }
        catch(const std::exception& e)
        {
            std::cout << e.what();
        }
    }
    

    【讨论】:

    • 它死了...(与将 mr 带到一些奇怪的 C++ 文件)
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多