switch statement clarification/error

heey, here's a code i made to test the switch statements but i'm not sure what went wrong!
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
/*

4-10 if-else-if vs. switch 
Set up something that uses a switch statement and an if-else-if to do exactly the same thing.
*/

#include <iostream>
#include <string>
using namespace std;

void main()
{
	string cool;
	string y;
	string n;
	
	cout << " If you type y, I will tell you you're cool. If you type n, I'll tell you you're not. <y/n> : ";
	cin >> cool;

	if (cool == "y")
	{cout << "You're Cool.\n";}
	
	else if ( cool == "n")
	{cout << "You're not cool.\n";}
	
	else 
	{ cout << "You didnt put a y or an n.\n";}

	cout <<  "I will do the same thing using a switch.\n";

	switch (cool)
	{
	case y:
		cout << "You're Cool.\n";
		break;
	case n:
		cout << "You're not Cool.\n";
		break;
	default:
		cout << "You didnt put a y or an n.\n";
		break;
	}

	
	system ("pause");
}
IN c++ main return int
int main()
ohhh. so apparently, i cant use strings with case. how would i change the strings into int?
I thing is beter to use char and cast it to int
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
#include <iostream>
#include <string>
using namespace std;

int main()
{
	char cool;
    cout << " If you type y, I will tell you you're cool. If you type n, I'll tell you you're not. <y/n> : ";
	cin >> cool;
	int choice=static_cast<int>(cool);

    switch (cool)
	{
	case 121:
		cout << "You're Cool.\n";
		break;
	case 110:
		cout << "You're not Cool.\n";
		break;
	default:
		cout << "You didnt put a y or an n.\n";
		break;
	}

}
No, it's better to use char, period.
1
2
3
4
5
6
7
8
9
10
char cool;
//...
switch(cool){
case 'y':
  //..
case 'n':
  //...
default:
  //...
}


BTW, you aren't using 'choice'
ne555 , i thought the cases cant be letters, but have to be a number/constant!

edit: would i use a stringstream?
Last edited on
Topic archived. No new replies allowed.