What is wrong with this code?

Hey guys, seeing as I've only been programming in C++ for a few weeks, I've looked around the forum and seen a brilliant thread with some beginner exercises. I've made a simple vending machine program that asks the user to key in an option of 1-5 for what drink they would like. Once the user has keyed in an option, they are then shown what option they have made. I made it using IF statements, and it worked perfectly. However, I'm having some trouble making the same program but with SWITCH statements. Can you guys have a look and tell me where I'm going wrong? (I'm using Anjuta IDE on Ubuntu 12.04 if you needed to know!)

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

#include <iostream>
using namespace std;

int main()
{
	
	int beverage;
	
	cout << "Please key in your favourite beverage: " << endl;
	cout << "1 - Coca Cola " << endl;
	cout << "2 - Diet Coke " << endl;
	cout << "3 - Sprite " << endl;
	cout << "4 - Fanta Orange " << endl;
	cout << "5 - Water " << endl;

	cin >> beverage;
	
	switch (beverage){
		case '1':
		cout << "You have chosen Coca Cola "; break;
			case '2':
			cout << "You have chosen Diet Coke "; break;
				case '3':
				cout << "You have chosen Sprite "; break;
					case '4':
					cout << "You have chosen Fanta Orange "; break;
						case '5':
						cout << "You have chosen water "; break;
	}
						

		
	
	return 0;
}
Last edited on
Remove the ' ' from the nums. With those there, they are chars, not ints.

On another note:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
switch (beverage){
		case 1:
		cout << "You have chosen Coca Cola "; break;

		case 2:
		cout << "You have chosen Diet Coke "; break;

		case 3:
		cout << "You have chosen Sprite "; break;

		case 4:
		cout << "You have chosen Fanta Orange "; break;

		case 5:
		cout << "You have chosen water "; break;
	}


Would probably be a better approach to indentation. Imagine you have 20 cases instead of just 5.

Edit: Or you can change the type of beverage to char instead of int.
Last edited on
beverage is a variable of type 'int', then the statement "case 'n' is wrong because of the embedded quotes ('n' denotes a variable of type char.) Replace 'n' with n:

example: case '1 ': wrong
case 1: correct


bye

ps-in the switch, always insert the default case
Last edited on
Olysold and ar2007 - you guys are stars. Thank you very much!
Topic archived. No new replies allowed.