Cola Machine

Hey! I was practicing my programming skills with some simple exercises because I am a beginner. Whenever I start debugging this program, if I choose 1, for example, it automatically gives me the default statement. If I choose 1, I should receive the cout << "You chose Sprite\n";. Please take a look at my code! Thanks (:

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
47
48
49
// Cola Machine.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <limits>

using namespace std;

int Answer;

int _tmain(int argc, _TCHAR* argv[])
{
	do{
	cout << "Please choose a number 1 through 5" << endl
		<< " Choose 1 for Sprite, 2 for Coke, 3 for Gatorade, 4 for Root Beer, or 5 for Water\n";
	cin >> Answer;
	switch (Answer)
	{
	case 'A':
		Answer = 1;
		cout << "You chose Sprite\n";
		break;
	case 'B':
		Answer = 2;
		cout << "You chose Coke\n";
		break;
	case 'C':
		Answer = 3;
		cout << "You chose Gaotrade\n";
		break;
	case 'D':
		Answer = 4;
		cout << "You chose Root Beer\n";
		break;
	case 'E':
		Answer = 5;
		cout << "You chose Water\n";
		break;
	default:
		cout << "Error. choice was not valid, here is your money back\n";
		break;
	}
	}while (Answer < 1 || Answer > 5 );
	
		system("PAUSE");
	return 0;
}
Hi !

The way that u wrote the prompt of "Please choose a number 1 through 5" means the user is expecting to press a number 1-5. But here:

case 'A':
U'r testing if the user pressed exactly a capitol letter 'A'. A simple fix is to change line 20 (and other 'case' lines) to case 1:

U'll also notice that u wont need lines 21,25,29,33,37 anymore since Answer has the value u want.

Extra:
Ur Answer variable is declared as an int so when u use 'cin' on line 17, it will try to put an int for whatever u pressed into Answer. So, if u'r not testing ints in ur switch statement then u'll have issues like u did...

Oh and put 'int Answer' between lines 13 and 14. Start with good habits ;)

Hope this helps !
Last edited on
Thanks a lot Soranz! Your suggestions were very helpful and now my program works (;
Topic archived. No new replies allowed.