用C ++编写一个菜单程序,使用户可以从选项列表中进行选择,如果输入的内容不是选项之一,则重新打印该列表

哈伦·高西(Haroon Ghawsi)

用C ++编写一个菜单程序,使用户可以从选项列表中进行选择,如果输入的内容不是选项之一,则重新打印该列表。

我尝试了以下代码,但未给出正确的结果。请帮忙。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string j;
    string x = "1. Option 1";
    string x1 = "2. Option 2";
    string x2 = "3. Option 3";
    cout << "please select from the menu " << endl;
    cout << x << endl;
    cout << x1 << endl;
    cout << x2 << endl;
    cin >> j;

    if(j == x)
    {
        cout << "You have selected the option " << j;
    }
    else if(j == x1)
    {
        cout << "if - x1 = You have selected the option " << j;
    }
    else
    {
        cout << "if - x2 = You have selected the option " << j;
    }
}
马辛尼

排队:

if(j == x)

您正在将用户输入j与整个字符串进行比较

"1. Option 1"

您想要将其与选项编号进行比较:

if(j == "1")

或者:

else if(j.size() >= 1 && j[0] == x1[0])
{
    cout << "if - x1 = You have selected the option " << j;
}

如果您要确保菜单字符串的第一个字符是选择此菜单的标识符。

另外,最后一个else无条件的位置是您应该重新打印选项列表的位置。

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

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

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档