been having problems running switch on my code which when I run it it says only "Could only chose 1,2, or 3. I have to make it run when chose different color.
// Lab 4 switch.cpp
// This program lets the user select a primary color from a menu.
// Alexis Meza Garcia.
#include <iostream>
using namespace std;
int main()
{
int choice; // Menu choice should be 1, 2, or 3
// Display the menu of choices
cout << "Choose a primary color by entering its number. \n\n";
cout << "1 Red \n" << "2 Blue \n" << "3 Yellow \n";
// Get the user's choice
cin >> choice;
// Tell the user what he or she picked
switch (choice)
{
case '1': cout << "\nYou picked red.\n";
break;
case '2': cout << "\nYou picked blue.\n";
break;
case '3': cout << "\nYou picked yellow.\n";
break;
default: cout << "\nCould only chose 1,2, or 3.\n";
}
return 0;
}
Please try to edit your post and put [code][/code] tags around your code.
Your actual problem is that are you confusing ints with chars (characters). C++ treats them somewhat compatibly (a character can be "upgraded" to an int), because they are actually both integer types, but they are different.
You have choice being an integer (a number).
However, in your switch statement, you have to select between '1', '2', and '3'.
'1' is a character. 1 is an integer.
See the difference in notation? Without the single quotes, 1 is just the number. But with single quotes, '1' is the human-readable character that represents the symbol for number 1.
Solution: change your switch cases to case 1:, case 2:, case 3: instead of case '1':, case '2':, case '3':.
(Alternative: Make choice be a char type instead of an int type.)
'1' is a character, and is stored as the ASCII value integer for the character '1'. (If you see http://www.asciitable.com/ you'll find out that the character '1' is actually equivalent to the integer value 49).