switch problem

Hello, forum.

I was reading through my C++ book and testing out each thing I've been taught, only to find myself met with an usual problem.

When you run this code, it seems to work fine so long as you use any integer, but if you enter something else the code will go straight to the default case, display the message, and then close instantly - ignoring the fact that I set up a cin at the end of the programming at the end to 'pause' the system.

Is there a way I can check that my input is an integer?

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
//Just a program to test the switch function.
#inlcude <iostream>
using namespace std;

int main ()
{
  int a;
  int choice; 
  cout << "Enter 1 or 2.\n";
  cin >> choice;
  
  switch (choice) 
  {
    case 1:
    cout << "You chose 1.\n";
    break;
  
    case 2:
    cout << "You chose 2.\n";

    default:
    cout << "You didn't choose 1 or 2.\n";
  }
  cin >> a;
  return 0;
}      


My thanks in advance,
Chris.
Last edited on
If you input invalid characters into cin, it will enter an error state, which causes the effects that you mentioned: skipping other cin statements, not intializing the variables, etc.

In order to check for errors, you should test the statement where you get input:
1
2
3
4
5
if(std::cin>>choice) {
  //input was OK
} else {
  //input had a problem
}


In order to fix the errors, you will want to first clear the errors by using std::cin.clear() then remove the invalid input.
Topic archived. No new replies allowed.