Switch Statement looping errors

Basically, I'm trying to learn C++, and I'm new at this. I know I can continue my program as it is, but I would rather know how to fix this problem now, for future issues.

So the switch statement works when I enter the single int values, but if I put 1 2 3 with spaces, the program opens all the cases. Also when I enter letters it loops non-stop. AND 312413431 43 also loops the program.

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
  #include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

int main()
{
    int grades;
    double gradeAverage;
    int choice;
    int maxCredits;
    char tryagain = 'y';

while (tryagain != 'n'){
    cout << "---------------------------------" << endl;
    cout << "|  WELCOME  - GRADE CALCULATOR  |" << endl;
    cout << "---------------------------------" << endl << endl;

    cout << "[1] - Enter module results\n---" << endl;
    cout << "[2] - Edit module results\n---" << endl;
    cout << "[3] - View final estimated grade\n---" << endl;


    cout << "Please enter a choice from the menu above:\n" << endl;
    cin >> choice;
    switch(choice){
            case 1:
                cout << "First case";
                break;
            case 2:
                cout << "Second Case";
                break;
            case 3:
                cout << "Third Case";
                break;

            default:
                cout << "You didn't select any option, would you like to try again? (Y/N)" << endl;
                cin >> tryagain;
                break;

    }
}

    return 0;
}
Your while loop at line 14 checks tryagain, but tryagain is only modified at line 39 (choice not 1,2 or 3). If you enter "1 2 3" you have three numbers in the input buffer. The first time through the loop, the cin at line 25 reads the "1". Since tryagain is still 'n', the loop at line 14 continues for a second iteration which reads the "2" from the input buffer. The loop continues for a third iteration, reading the "3" from the input buffer.
Topic archived. No new replies allowed.