How to display error when a char is entered

How can I make my program display an error when a char (a,b,c) is entered in the menu selection. At the moment, when I enter a char, it displays the error message BUT in a continuous loop. Here is what my code looks like:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int menu;
    string studentID[] = {"P1001", "P1002"};
    float studentMark[] = {78.50, 66};
    int totalStudents=0;
    float totalMarks=0;
    float averageMark;

        
    cout << "MAIN MENU\n"
         << "0. Exit         1. Statistics\n"
         << "2. Enter mark   3. Find mark\n"
         << "------------------------------\n"
         << "Your choice -> ";
    cin >> menu;

  while (menu != 0)
  {
    switch (menu)
    {
           case 1:
                for(int j=0;j<2;j++)
                {
                   totalMarks+=studentMark[j];
                   totalStudents++;
                }
                averageMark=totalMarks/totalStudents;
                cout << "Mean or average: " << averageMark <<endl;
                break;
           case 2:
                cout << "Please enter Student ID: ";        
                break;
           case 3:
                cout << "Find mark" << endl;
                break;
           default:
                   cout << "Invalid selection. Please make a selection between 0-3.\n"
                        << endl;
    }    
system("Pause");
    cout << "MAIN MENU\n"
         << "0. Exit         1. Statistics\n"
         << "2. Enter mark   3. Find mark\n"
         << "----------------------------\n"
         << "Your choice -> ";
    cin >> menu;
  }
  
return 0;
}


It would be greatly appreciated if somebody could help me please.
Hi.......

As Bazzy has correctly pointed out, do not use cin because it leaves the remnant \n in the input buffer. It doesn't allow you to validate the input

Use getline instead to scan all input as string, then convert accordingly.

http://www.cplusplus.com/forum/articles/6046/
Topic archived. No new replies allowed.