Switch 语句读取 C++ 中的每个输入

T.243

我有这个 switch 语句,用于允许用户选择一个选项。当用户输入 9 时它退出。但问题是当我输入类似“ah2”的东西时,它会读取“a”然后打印错误消息,接下来是“h”和错误消息,然后是 2。程序应该当用户输入此类输入时停止,并应要求输入不同的输入。

这是我的代码。

void menu()
{

    int choice = 0;

    cout<<"\nWelcome to the program menu."<<endl;
    cout<<"Choose the operation you would like to execute."<<endl;
    cout<<"1. Create "<<endl;
    cout<<"2. Look items "<<endl;
    cout<<"3. See "<<endl;
    cout<<"4. Get "<<endl;
    cout<<"5. See the value "<<endl;
    cout<<"6. Insert an item"<<endl;
    cout<<"7. Delete an item"<<endl;
    cout<<"8. Destroy "<<endl;
    cout<<"9. Press -1 to exit the program"<<endl;

    cout<<"Enter your choice: "<<endl;
    cin>>choice;

   while(choice != 9)
    {
        switch (choice)
        {
case 1:
            cout<<"You choose one"<<endl;
            break;
        case 2:
            cout<<"You choose two"<<endl;
            break;
        case 3:
            cout<<"You choose three"<<endl;
            break;
        case 4:
            cout<<"You choose four"<<endl;
            break;
        case 5:
            cout<<"You choose five"<<endl;
            break;
        case 6:
            cout<<"You choose six"<<endl;
            break;
        case 7:
            cout<<"You choose seven"<<endl;
            break;
        case 8:
            cout<<"You choose height"<<endl;
            break;
        case 9:
            cout<<"You choose nine"<<endl;
            break;
        default:
            cout<<"You have not entered a number proposed. Retry. "<<endl;
            choice = 0;
            break;
        }
        cin.clear();
        cin.ignore();
        cout<<"Enter your choice : "<<endl;
        cin>>choice;
    }
    cout<<"\nYou have entered the exist option end the program"<<endl;
}
软香草

更改cin.ignore()cin.ignore(INT_MAX, '\n')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章