Switch Statement: Setting a variable
Jan 26, 2012 at 6:37pm UTC
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;
}
Jan 26, 2012 at 6:40pm UTC
while ((choice < 1) || ( choice > 6))
Look closely at this statement and think about the switch ranges
Jan 26, 2012 at 6:46pm UTC
I have tried setting it to
while((choice > 1) || ( choice < 6))
but it always resorts to the default..
Jan 26, 2012 at 6:49pm UTC
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.
Jan 26, 2012 at 6:55pm UTC
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?
Jan 26, 2012 at 7:11pm UTC
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:
Jan 26, 2012 at 7:15pm UTC
Thanks for your help- I reworked the while and fixed the case statements and it works great!
Topic archived. No new replies allowed.