Beginner: Switch statement

Can someone help me fix my switch statement

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

using namespace std;


int main(){

string doucheAgaintry;

cout << "Is Againtry a bored douche troll with no life ?" << endl;

cin >> doucheAgaintry;

switch(doucheAgaintry)
{
	case 'Yes':
	cout << "Correct. He has no life and miserable";
	break;
	
	case 'No':
	cout << "You must be wrong";
	break;
	
	default:
	cout << "Choose a new answer";
	break;
}


}

Use an if-else construct for strings.
Use quotation marks (double quotes) for string literals: "xyz"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

int main()
{
    std::string answer ;
    std::cin >> answer ;

    // note: double quotes ""
    if( answer == "Yes" ) { /* ... */ }

    else if( answer == "No" ) { /* ... */ }

    else { /* ... */ }
}
Hello cblack618,

The first thing you have to understand is the the switch condition can only be an "int" or a "char" which is a type of "int".

Change string doucheAgaintry; to char doucheAgaintry; and adjust your prompt to say that (Y/N) is all you need for input.

In the case statements change 'Yes' to 'Y'. BTW 'Yes' is a string and should be in double quotes not single quotes. Single quotes are for one character.

Andy
It's good to see you're reviewing the basics before trying to tackle more complicated things like classes and polymorphism. Good luck!
Thanks Andy
Hello cblack618,

You are welcome.

Now that you understand that better here is the changes I made:
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>
#include <string>

using namespace std;

int main()
{
	char doucheAgaintry;

	cout << "Is Againtry a bored douche troll with no life ? (Y/N) ";

	cin >> doucheAgaintry;

	switch (doucheAgaintry)
	{
		case 'y':  // <--- Catches both letter cases.
		case 'Y':
			cout << "Correct. He has no life and is miserable";
		break;

		case 'n':
		case 'N':
			cout << "You must be wrong";
		break;

		default:
			cout << "Choose a new answer";
			break;
	}
}


Andy

Edit: Sorry indenting went strange. Needed to fix.
Last edited on
Topic archived. No new replies allowed.