-
Case statement problem
I'm completely new to using case statements in C++ so bear with me. I'm trying to do a very simple case statement that will display the user to the user what grade they have got.
Code:
#include <iostream>
using namespace std;
int main()
{
int grade;
cout << "Please enter your grade";
cin >> grade;
switch (grade)
{
case grade >= 70:
cout << endl << "You got a grade A";
break;
case grade >= 60:
cout << endl << "You got a grade B1";
break;
case grade >= 50:
cout << endl << "You got a grade B2";
break;
case grade >= 40:
cout << endl << "You got a grade C";
break;
case grade >= 30:
cout << endl << "You got a grade D";
break;
case grade == 30:
cout << endl << "You Failed";
}
return 0;
}
I know it is the "grade >=" ect parts that are wrong but I dont know how to right it so that it works. Anyone help?
Thanks.
-
Switch case statements can only contain integers or chars as case statements.
ie:
Code:
case 1:
// code
break;
or
case 'A':
case 'a':
// code
break;
aslo, supply a default case to catch an error
default:
cout << "\nERROR: Invalid input!" << endl;
break;
-
It may be easier to do this:
Code:
cout << "Enter your grade: ";
cin >> grade;
if ( grade >= 50 )
cout << "\nYou got a D" << endl;
-
Yeah, it's the job for if statements, not switches.
-
To use a switch you need to have a single constant expression for each case. So you can't do case grade <= 10. you must do case 1: , case 2: ...
But you can change your expression grade/10 to get the tenth's place digit of grade.
Eg:
Code:
switch(grade/10)
{
case 9:
case 8:
cout << endl << "You got a grade A";
break;
case 6:
cout << endl << "You got a grade B1";
break;
case 5:
cout << endl << "You got a grade B2";
break;
case 4:
cout << endl << "You got a grade C";
break;
}
-
Thnaks got it working now.