Switch Statements Trouble

Hello, I'm currently taking a C++ course which I thought would be a worthwhile class. I know how to do switch statements with a single character as the case. However when it comes to checking a variable for numerical conditions with case it's a completely different story. My instructor wants me to correct the errors with the code below, but I am clueless what to change it to. The book only covers switch case statements with a single character.

Normally in this case I would just use if, else if, and else (if needed) but for the other questions where I had to find errors they never made me change the whole script completely so I am a bit against using it.

Some suggestions on what to change it to and an explaination would be greatly appreciated.

The error I receive when I input the code they provided

error: 'testScore' cannot appear in a constant-expressi
on

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
  //This program uses a switch-case statement to assign
//letter grades to a numeric testScore

#include <iostream>
using namespace std;

int main()
{
   int testScore;
   
   cout <<"Enter your test score and I will tell you\n";
   cout <<"the letter grade you earned: ";
   cin>> testScore;
    switch (testScore)
    {
        case (testScore < 60.0):
            cout << "Your grade is F.\n";
            break;
        case (testScore < 70.0):
            cout << "Your grade is D.\n";
            break;
        case (testScore < 80.0):
            cout << "Your grade is C.\n";
            break;
        case (testScore < 80.0):
            cout << "Your grade is B. \n";
            break;
        case (testScore < 90.0):
            cout <<"Your grade is A.\n";
        default: 
            cout << "That score isn't valid\n";
    return 0;
    }
}

case labels should be compile-time integral constants. In your case switch is completely unsuited for you.
The condition within a case has to be a constant-expression.

case (testScore < 90.0) is wrong because testScore < 90.0 could be true OR false; has MORE THAN one outcome.
case (90) is correct because it has ONLY one outcome which is 90

To do this in a switch statement, you would need to have about 60 cases. An if-else would be better.
Topic archived. No new replies allowed.