Why is this code snippet infinitely looping?

前提是你 提交于 2019-12-12 02:53:45

问题


I'm fairly new to programming, and I'm trying to filter inputs from cin (for no particular reason; It is the only input method I know of right now) such that one can only enter 1-10 and get the "positive" response. Here is my code:

#pragma region Check cin is a valid input (an integer between 1 and 10, not a string or number out of range)
int input;
bool valid2=false;
    while (!valid2)
    {
        cout << "Enter an integer (1-10): ";
        cin >> input;
        if (!cin || input > 10 || input < 1)
        {
            cout << "Error: Invalid. Try again." << endl << endl;
            cin.ignore(numeric_limits<streamsize>::max());
            cin.clear();
        }
        else
        {
            valid2 = true;
        }
    }
#pragma endregion

Ignore the "pragma", I have one test script with blocks for each little experiment to save me time and this is just how I collapse them when they're no longer valid.

My problem (among others) is that when I enter a non-integer such as f, it loops infinitely with "Error: Invalid. Try Again", and I can't figure out why. I thought maybe since input became defined, it was running past cin when it comes back around. But I checked an isolated example, and cin let me specifically redefine input before continuing.

Sidebar: Speaking of pragma, does anyone have a better method for this in c++? Aside from making individual methods, because most of my tests can just run inside main.

EDIT: I've switched cin.ignore(...) and cin.clear() and now the program can properly filter the inputs; however now, it doesn't loop back at all. After giving me "Error: Invalid. Try again.", it hangs where it should ask me again to enter the integer.


回答1:


Your original code has TWO problems (at least as far as I've spotted - not guaranteeing there aren't any more):

  1. The order of cin.clear() and cin.ignore() - cin.clear() should be before cin.ignore(), or cin.ignore() will do nothing.
  2. The cin.ignore(numeric_limits<streamsize>::max()); is reading until the delimiter, which defaults to EOF - in other words, no matter what input is in the buffer, or entered after, it keeps on accepting it.

To fix both problems use this:

  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), '\n');

that will read until the end of the current line, which is probably more along the lines of what you want.

Oh, and change:

    cin >> input;
    if (!cin || input > 10 || input < 1)

to:

    if (!(cin >> input) || input > 10 || input < 1)


来源:https://stackoverflow.com/questions/18131903/why-is-this-code-snippet-infinitely-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!