在C ++中切换语句错误

时间:2013-07-21 08:03:29

标签: c++

大家好,有人请帮我解决这个问题?它运行但它不执行它应该执行的任务。运行后,它会自动跳转到默认语句并跳过案例。请帮我解决这个问题!

#include<iostream.h>
#include<conio.h>

using namespace std;


int main()
{
    int choice;
    char nbaPlayer, tele, food, subject, x;

    cout << "This program determines your favorites.\n\n";
    cout << "Please select the number of your corresponding choice.";
    cout << "\n1. NBA Player";
    cout << "\n2. Teleserye";
    cout << "\n3. Food";
    cout << "\n4. Subject";
    cout << "\n5. Exit";

    switch (choice)
    {
        case 1:
            cout << "You have chosen NBA Player.\n";
            cout << "Please enter your favorite NBA Player. \n";
            cin >> nbaPlayer;
            cout << "Your favorite NBA player is " << nbaPlayer;
            break;

        case 2:
            cout << "You have chosen Teleserye.\n";
            cout << "Please enter your favorite teleserye. \n";
            cin >> tele;
            cout << "Your favorite teleserye is " << tele;
            break;

        case 3:
            cout << "You have chosen food.\n";
            cout << "Please enter your favorite food. \n";
            cin >> food;
            cout << "Your favorite food is " << food;
            break;

        case 4:
            cout << "You have chosen subject.\n";
            cout << "Please enter your favorite subject. \n";
            cin >> subject;
            cout << "Your favorite subject is " << subject;
            break;

        case 5:
            cout << "You chose to exit.\n";
            break;

        default:
            cout <<"\nInvalid input";

    }

    getch();
}

1 个答案:

答案 0 :(得分:11)

你忘记了:

cin>>choice

显示可用选项后。因此,当您从未为选择分配价值时,它始终会选择default