-1

I have a small program written in C++ that requests command line input for the user's grade. If the input is valid (i.e. a number between 0 and 100), a switch is called to print something out based on the user's grade, and then the program exits successfully.

If the user enters a number that isn't a valid grade, the program successfully loops back and asks for valid input until the user enters an appropriate grade.

However, if the user enters a String that isn't a number at all, such as "no", the loop infinitely requests a valid grade without ever stopping to take input, ultimately crashing the command line.

The complete program:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(int argc, char** argv) {

cout << "\nEnter your grade: ";

int grade;

// Infinite input loop.
while(true) {
    // Is the String a valid grade?
    if(cin >> grade && grade >= 0 && grade <= 100) {
        switch(grade / 10) {
            case 10:
            case 9:
                cout << "A is for \"Awesome\"!";
                break;
            case 8:
                cout << "B is okay.";
                break;
            case 7:
                cout << "C isn't okay.";
                break;
            case 6:
                cout << "Bad luck.";
                break;
            case 5:
            case 4:
            case 3:
            case 2:
            case 1:
                cout << "Ouch!";
                break;
        }
        cout << "\n\n";
        break;
    } else {
        cout << "Please enter a valid grade: ";
    }
}
}
Sam Claus
  • 1,807
  • 23
  • 39

1 Answers1

1

That is because the stream enters a failure state. When the fail bit is set in the stream all operations will fail. You need to call clear() on the stream to clear out the error flags and then you need to remove any extra input that could still be in the stream. You can do that with

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

You will need to include the <limits> header for this.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402