0

I'm currently learning about switches in C++, so I created a grading program that will output a specific message based on the grade entered. Below is the code:

#include <iostream>
using namespace std;

int main()
{
    char student_grade;

    cout << "Enter student's grade:" << "\n";   
    cin >> student_grade;

    // switch statement for a simple grading system
    switch(student_grade)
    {
        case A:
            cout << "You have passed with a distinction!";
            break;

        case B:
            cout << "You have a grade B,congrats.";
            break;

        case C:
            cout << "Average grade,you can do better.";
            break;

        default:
            cout<<"NIL grade";
            break;
    }

    return 0;
}

I get this error once I run it, what did I do wrong?

/root/Desktop/practise.cpp: In function ‘int main()’:
/root/Desktop/practise.cpp:14:6: error: ‘A’ was not declared in this scope
14 | case A:
| ^
/root/Desktop/practise.cpp:17:6: error: ‘B’ was not declared in this scope
17 | case B:
| ^
/root/Desktop/practise.cpp:20:6: error: ‘C’ was not declared in this scope
20 | case C:
| ^
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Andrew Mbugua
  • 437
  • 1
  • 6
  • 16
  • It seems you might need to take a step back, and review your class notes, tutorials or invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). Think a little bit about the difference between e.g. `A` and `'A'`. – Some programmer dude Mar 01 '20 at 19:11
  • yes yes @Remy Lebeau ,I now realise my error A and 'A' – Andrew Mbugua Mar 02 '20 at 08:17

2 Answers2

2

In the switch case, the character cases should be written in ' '. E.g. 'A', 'B'. There is a difference between A and 'A', 'A' is a character literal. It's of char type with value 97 on most of the systems. The corrected code will be:-

#include<iostream>

using namespace std;

int main()

{

char student_grade;

cout<<"Enter student's grade:"<<"\n";

cin>>student_grade;

// switch statement for a simple grading system

switch(student_grade)

{
case 'A':
cout<<"You have passed with a distinction!";

break;
case 'B':
cout<<"You have a grade B,congrats.";

break;

case 'C':

cout<<"Average grade,you can do better.";

break;

default:

cout<<"NIL grade";
break;

}


  return 0;

}
Saksham Dubey
  • 134
  • 2
  • 18
1

Simpe put it in ' ' because thats necessary for chars than it will compile. Without that its just a variable.

#include<iostream>

using namespace std;

int main()

{

char student_grade;

cout<<"Enter student's grade:"<<"\n";

cin>>student_grade;

// switch statement for a simple grading system

switch(student_grade)

{
case 'A':
cout<<"You have passed with a distinction!";

break;
case 'B':
cout<<"You have a grade B,congrats.";

break;

case 'C':

cout<<"Average grade,you can do better.";

break;

default:

cout<<"NIL grade";
break;

}


  return 0;

}
Ingo Mi
  • 999
  • 12
  • 26