首页 > 解决方案 > 带有选项的菜单列表

问题描述

我正在尝试在程序中制作选择列表,现在我对用户输入错误输入时会发生什么感到困惑。

我试过用do loop 来做(我循环了 switch 语句)。另外,尝试将变量设置为整数和字符,但都有问题。Char只需要一个字符,当你写多个字符时,它会自行检查每个字符。使用int输入错误时 ,我会得到一个无限循环的菜单功能。

另外,尝试在stackoverflow中使用我在这里找到的cin.fail(),但没有成功。

void menu()
{
if(!isEmpty())
{
    showStack();
}
else
{
    cout << "stekas tuscias!" << endl;
}

cout << "---------------------------" << endl;
cout << "1. Iterpti i steka (push)" << endl;
cout << "2. Pasalinti is steko (pop)" << endl;
cout << "3. Issaugoti steka" << endl;
cout << "4. Issaugoti steka ir uzdaryti programa" << endl;
cout << "---------------------------" << endl;
cout << "Jusu pasirinkimas: ";

char key;
cin >> key;
switch(key)
{
    case '1':
    {
        cout << "Irasykite reiksme i konsole: ";
        int data;
        cin >> data;
        cout << endl;
        push(data);
        break;
    }
    case '2':
    {
        cout << endl;
        pop();
        break;
    }
    case '3':
    {
        write();
        cout << "--------" << endl;
        cout << "Stekas issaugotas!" << endl;
        cout << "--------" << endl;
        menu();
        break;
    }
    case '4':
    {
        write();
        break;
    }
    default:
    {
        cout << "Tokio pasirinkimo nera!" << endl;
        cout << endl;
        key = '\0';
        menu();
        break;
    }
}
}

如果需要,我的整个代码:https ://pastebin.com/Xv1HE0Mh

标签: c++switch-statement

解决方案


我确定为什么 cin.fail() 或 (!cin) 不适合你。但是,你可以这样做。而且,我也确定存在这种问题。

template <class T>
int check (T ch)
{
    if (ch >= 'a' && ch <= 'Z') return 0;
    else return 1;
}

接着。

main ()
{
.
.
char c;
cin.get (c); //Note here!!
if (check (c)) {...}
else {...} //You can use goto.
.
}

推荐阅读