开发者

Why such loop does not catch error when inputting a string?

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

Why such loop does not catch error when inputting a string? How to fix it? I can use std::string and Boost library and reg exp.


Assuming are trying to read in an integer using std::cin and detect if the user input a string instead:

If the user does input a string, an exception will not be thrown (which is why your code doesn't work as expected). Instead, the input will be left in the buffer, and cin will be in an error state. The next cin >> will read the same value from the buffer in an endless loop, unless you clear the error state and buffer before the next iteration.

See this article which explains exactly how to read in an integer (and what happens when a string is input instead) as well as how to clear the error state and buffer.


The stream library doesn't throw exceptions by default. You have to enable it first like in the following example:

#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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜