Help me with my Switch statement.

here is my switch statement, it has a small problem. when I run this it does both cases, thus providing a wrong answer. I know I'm probably just missing something silly but any help is appreciated. Oh, I only copied the relevant portions of my code. d is calculated in the code prior to the question, it runs normally. I tried if else, but that just messed me up a lot. is there any easier way to do this?


int main()
{
int a, b, c,d, e, f, g;
int answer;




cout << "Have you already celebrated your birthday this year? please answer 1 for yes and 2 for no. \n ";
cin >> answer;

switch (answer) {
case 1:
e = d + 1752;
cout << "then we add 1752 to the number and get: \n " << e;

case 2:
e = d + 1750;
cout << "Then we add 1750 to the number and get: \n " << e;

}
You need "break":
1
2
3
4
5
6
7
8
9
10
11
12
13
int a = // a small random number;

switch (a)
{
case 1:
  cout << "The number is 1\n";
  break;
case 2:
  cout << "The number is 2\n";
  break;
default:
  cout << "The number is too high\n";
}


switch case is the way to go for something like that.

I would recommned answer being a char, less bug prone
1
2
3
4
5
6
7
8
9
char answer;
cout << "Please type a number: ";
cin >> answer;
cin.ignore(80, '\n');  // ignore all but the first character

switch(answer)
{
case '1':  // ...
}

you must end them with break; statements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
int a, b, c,d, e, f, g;
int answer;




cout << "Have you already celebrated your birthday this year? please answer 1 for yes and 2 for no. \n ";
cin >> answer;

switch (answer) {
case 1:
e = d + 1752;
cout << "then we add 1752 to the number and get: \n " << e;
break;

case 2:
e = d + 1750;
cout << "Then we add 1750 to the number and get: \n " << e;
break;

}


You can even add a default;, to handle wrong inputs.
eg:
1
2
3
4
default:
        cout<<"Wrong input.";
        cin.get();
        break;
thanks, I totally forgot about breaks, dunno why.

I'll try out your version of the answer and see if it helps me a little more. this is a really short, really simple program for me to test what I've learned so far.
OK, the default was also a very helpful item, however, how do i get that to go back up and "repeat" the request for the input?
use do...while loop

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
#include <iostream>

using namespace std;

int main()
{
int a, b, c,d, e, f, g;
int answer;

do {
cout << "Have you already celebrated your birthday this year? please answer 1 for yes and 2 for no and 0 to close. \n ";
cin >> answer;

switch (answer) {
case 1:
e = d + 1752;
cout << "then we add 1752 to the number and get: \n " << e;
break;

case 2:
e = d + 1750;
cout << "Then we add 1750 to the number and get: \n " << e;
break;

default:
cout<<"Wrong input";
cin.get();
} 
}while(answer!=0);
}
Last edited on
Topic archived. No new replies allowed.