cin for an int inputing a char causes Loop that is supposed to check input to go wild

后端 未结 3 1543
一向
一向 2020-11-29 10:03

This is a function of my game it will ask for input and cin into \"iAuswahl\"! Then the while loop is checks if it is one of the Values i want 1-9 if not it activates and is

3条回答
  •  时光取名叫无心
    2020-11-29 10:32

    When an error occurs when reading from a stream, an error flag gets set and no more reading is possible until you clear the error flags. That's why you get an infinite loop.

    cin.clear(); // clears the error flags
    // this line discards all the input waiting in the stream
    cin.ignore(std::numeric_limits::max(), '\n');
    

    Also, it's wrong to use the results of input operation if you don't know whether the read succeeded in the first place. You can't make assumptions about the value of iAuswahl. That's one of most often made errors by newbies using streams. Always check if the input operation was ok. This is most easily done by using operator>> in boolean context:

    if (cin >> some_obj) {
        // evaluates to true if it succeeded
    } else {
        // something went wrong
    }
    

    And, my oh my, this line

    while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)
    

    can be just this:

    while (iAuswahl < 1 || iAuswahl > 9)
    

    A correct loop could look something like this:

    while (true)
    {
        if ((cin >> iAuswahl) && (iAuswahl >= 1) && (iAuswahl <= 9)) break;
        std::cout << "error, try again\n";
        cin.clear();
        cin.ignore(std::numeric_limits::max(), '\n');
    }
    

提交回复
热议问题