+ 1

Problem With Switch statement - c++

Guys look at this code and tell me where is the problem which in all value it shows invalid number which is default. #include <iostream> using namespace std; int main() { char marks; cout<<"Enter your Marks: "<<endl; cin>>marks; switch(marks){ case 'marks<=100 && marks>=90': cout<<"Your Grade Is A"<<endl; break; case'marks<90 && marks>=75': cout<<"Your Grade Is B"<<endl; break; case'marks<75 && marks>=50': cout<<"Your Grade Is C"<<endl; break; case'marks<50 && marks>=0': cout<<"You Failed!"<<endl; break; default: cout<<"Invalid number"<<endl; } return 0; }

11th Jun 2018, 5:59 AM
AMANULLAH
AMANULLAH - avatar
7 Antworten
+ 3
You must remove single quotes since grade is a number not a character! I think you didn't get the point. Let's look at the following example int grade; cin >> grade; // Here, you pass a single value as your grade. // Each case can only check a single value. // What if the grade is 95? Do you want to put 10 cases from 90 to 100?! switch (grade) { case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: cout << "What a stupid solution for getting Grade A!"; break; }
11th Jun 2018, 6:39 AM
Babak
Babak - avatar
+ 3
You are simply abusing the language facility by trying to stuff the condition evaluations instead of a single quantity in front of each case. Switch...case conditional block has been designed for the purpose of making the program more readable and easy to track but also with a cost. You can't perform complex evaluation like what you do normally with if...else statement. In other word, having switch...case as a solution for grade evaluation is a terrible idea at best. Try and reimplement it with if...else or other mechanism.
11th Jun 2018, 6:18 AM
Babak
Babak - avatar
+ 3
Good to hear that but I'm afraid some people exactly don't know the nature of your program. "One solution doesn't fit to ALL problems". You definitely need to study more.
11th Jun 2018, 6:57 AM
Babak
Babak - avatar
+ 2
thank you
11th Jun 2018, 7:04 AM
AMANULLAH
AMANULLAH - avatar
0
a single quantity also not works in my code
11th Jun 2018, 6:28 AM
AMANULLAH
AMANULLAH - avatar
0
well thanks, (my problem was char and those singe quotes.) solved. actually i did it in if-else but wanted to try it in switch because some people says that switch is a good replacement for if-else.
11th Jun 2018, 6:44 AM
AMANULLAH
AMANULLAH - avatar
0
Switch statement can only be used for matching a variable with a list of intergers or constants .. You can't write logical expression with case
11th Jun 2018, 7:01 AM
Aveek Bhattacharyya
Aveek Bhattacharyya - avatar