Switch Statement: Setting a variable

closed account (NU9GNwbp)
Hi, This should be really easy- what am I doing wrong? Why wont the switch statement set the variable- is it out of scope? How can I fix it?

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <string>
using namespace std;


int main()
{
	string Name = "no Name";
	string CDtype = "Default";
	float cost = 0.0;

	cout << "Enter a name ";
	cin >> Name;
	int choice;
	
	cout << "Enter a Cd Type | 1. Game | 2. Word | 3. Compiller | 4. Spreadsheet | 5. Dbase | 6. Presentation |"<<endl;
	cin >> choice;

	while((choice < 1) || ( choice > 6))
	{
		switch(choice)
		{
	case '1':
		{
		CDtype = "Game";
		break;
		}
	case '2':
		{
		CDtype = "Word";
		break;
		}
	case '3':
		{
		CDtype = "Compiller";
		break;
		}
	case '4':
		{
		CDtype = "Spreadsheet";
		break;
		}
	case '5':
		{
		CDtype = "Dbase";
		break;
		}
	case '6':
		{
		CDtype = "Presentation";
		break;
		}
	default :
		cout << "Incorrect input. Please try again.";
		cin >> choice;
		}
	}

	cout << "Please enter CD cost";
	cin >> cost;
	
	while(cost <= 0.0){
		cout << "Incorrect input. Please try again.";	
		cin >>cost;
	}
	


	cout << "This is the name: " << Name <<endl;
	cout << "This is the type: " << CDtype <<endl;
	cout << "This is the cost: " << cost <<endl;

	system("pause");
	return 0;
}
 
while((choice < 1) || ( choice > 6))


Look closely at this statement and think about the switch ranges
closed account (NU9GNwbp)
I have tried setting it to

while((choice > 1) || ( choice < 6))

but it always resorts to the default..
1
2
cout << "Enter a name ";
	cin >> Name;


You know if you enter any whitespace it will only grab the first string and leave the whitespace and rest of the typed chars in the buffer. If this is only intended for 1-word names then ignore this comment.
closed account (NU9GNwbp)
I am focusing on the switch statement- and have not begun to setup my stream output yet.
What am I doing wrong with the while loop?
My bad. I should have caught it straight away but...

1
2
int choice;
cin >> choice;


If the user enters 1, it will not be '1' (ascii 49). Take the ''s off of you case statements so they look like:

1
2
3
case 1:
case 2:
...

closed account (NU9GNwbp)
Thanks for your help- I reworked the while and fixed the case statements and it works great!
Topic archived. No new replies allowed.