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