Dec 29, 2012 at 11:03pm Dec 29, 2012 at 11:03pm UTC
I am confused on why while (! (cin >> num_grade)) would be false on the condition the input was not a number, being num_grade as type int?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
#include <string>
using namespace std;
bool check(int grade, int low, int high){
if (grade >= low && grade <= high)
return (true );
else
return (false );
}
char num_to_ch(int grade){
if (check(grade, 0, 59))
return 'F' ;
else if (check(grade, 60, 69))
return 'D' ;
else if (check(grade, 70, 79))
return 'C' ;
else if (check(grade, 80, 89))
return 'B' ;
else if (check(grade, 90, 100))
return 'A' ;
else
return 'x' ;
}
int main(){
string error = "That is invalid input" ;
int num_grade;
char grade;
cout << "Enter grade in number [0-100]" << endl;
while (! (cin >> num_grade) || num_grade < 0 || num_grade > 100){
cout << error << endl;
cin.clear();
cin.ignore(1000, '\n' );
}
grade = num_to_ch(num_grade);
cout << grade;
}
Last edited on Dec 29, 2012 at 11:06pm Dec 29, 2012 at 11:06pm UTC
Dec 29, 2012 at 11:06pm Dec 29, 2012 at 11:06pm UTC
Because the C++ extraction operator>> knows that a numeric value requires a numeric input. If it doesn't get a valid input then there was an error reading the stream, hence the proper error flag was set.
Dec 29, 2012 at 11:10pm Dec 29, 2012 at 11:10pm UTC
ok i didnt know that it has the ability to do that by itself, thanks.