I would suggest reading from cin in the while test, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
cout << "Please enter a grade: ";
while(cin >> grade && grade != 999) {
if(grade < 0 || grade > 100)
cout << "Invalid grade. ";
else {
total += grade;
++count;
}
cout << "Enter the next grade: ";
}
cin.clear(); //in case of cin failure
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //eat the remainder character(s)
|
Why? Consider the following input:
100
78
55
84
c
The 'c' will cause cin to fail in both examples.
However, the loop posted by Volatile Pulse would cause the following issues:
1) the program would enter an infinite loop (grade stays at 84),
2) for each loop through, 84 would be added to total, and the count would increase, despite no / invalid input.
In my loop, the program is protected from an infinite loop, and data integrity is protected.
Edit: added cin.ignore(...) call.