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;
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': // ...
}
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:
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.
#include <iostream>
usingnamespace 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);
}