+ 1

How do i get C++ to output an error code using if statement?

I created a code to determine the letter grade by inputting a numeric value. However, i am trying to test grades above 100 and below 0. I wrote an OR condition and still not getting a output of my error.. The code is below: int main() { int grade = 0; cout <<"Enter a numeric grade: "; cin >> grade; if (grade >=90 && grade <=100) cout << "Letter grade is A"; else if (grade >=80) cout << "Letter grade is B"; else if (grade >=70) cout << "Letter grade is C"; else if (grade >=60) cout <<"Letter grade is D"; else cout <<"Letter grade is F"; if (grade < 0 || grade > 100) cout << "Error: Invalid numeric value"; } output: Enter a numeric grade: 456 Letter grade is BError: Invalid numeric value

23rd May 2018, 2:10 PM
shamizzle
6 Answers
+ 1
You have to check for invalid input before and if check is negative (grade is in range) you can proced to get grade letter: if(grade<0 || grade>100){ // INVALID VALUE }else{ // Here you can get grade letter } P.S. Use always braces for more than simple expressions for easy reading
23rd May 2018, 2:18 PM
KrOW
KrOW - avatar
+ 1
Max Yes you have right.... I dont understand because most users post codes "inline" when exist the code section that help to read and debug codes
23rd May 2018, 2:36 PM
KrOW
KrOW - avatar
+ 1
if else ladder ...followed by if statement is confuising..your letter grade on checking 456 results in grade B and invalid numeric because 456>=80 is true that means your upper bound is not closed...it is always better way to use switch staments instead of if else ladder. it is better to close if and else if on expected results..and else on unexcepted result or data. https://code.sololearn.com/cdnQ4dLdYH4Y/?ref=app just little edit just close the else if statements.
23rd May 2018, 2:38 PM
Sunil Thakali
Sunil Thakali - avatar
0
Your condition grade >= 80 is true if grade is over 100 so the error handling is only reached if grade < 0 and please use curly braces this is very hard to read
23rd May 2018, 2:26 PM
Max
Max - avatar
0
Max if grade < 60 (then < 0 also), code runned is else block with letter F grade and next error handling block
23rd May 2018, 2:32 PM
KrOW
KrOW - avatar
0
Oh yeah you are right I didn’t even read that far the lack of {} and else if was to painful
23rd May 2018, 2:34 PM
Max
Max - avatar