C ++开关始终为默认值

时间:2016-09-17 21:01:01

标签: c++

当我使用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;
}

1 个答案:

答案 0 :(得分:4)

在您的选择中,您的case是一个字符,但您选择的是整数。

所以改变

case '1'

case 1

或者改变

int choice;

char choice;