当我使用switch
时,无论输入的值如何,它始终会打印default
值。我在每break
个语句后添加了case
。我该如何解决?
// Lab 4 color.cpp
// This program lets the user select a primary color from a menu.
#include <iostream>
#include <string>
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 << "You entered an invalid option. Please run again and choose 1, 2, or 3.\n";
break;
}
return 0;
}
答案 0 :(得分:4)
在您的选择中,您的case
是一个字符,但您选择的是整数。
所以改变
case '1'
到
case 1
或者改变
int choice;
到
char choice;
等