【问题标题】:Trouble with limiting user's input限制用户输入的问题
【发布时间】:2016-07-21 03:52:13
【问题描述】:

对于以下内容,我试图将用户输入限制为仅 Y 或 y 或 N 或 n。请按照我的 cmets 上的代码,这样我就可以指出问题所在。我是这个论坛的新手,我对编程充满热情,如果有人可以请帮助我。谢谢。 while 循环(不是 do-while 循环)是我遇到问题的部分。我想也许我没有正确使用 != 。我还没有什么太高级的东西,我现在的班级只是入门级。

    cout << "Would you like to use this program again?: ",
    cin >> ans;

    if(ans =='Y'||ans =='y'||ans =='N'||ans =='n')
        break;
    else //This is where I'm having problem with.
        while (ans != 'Y'||ans != 'y'||ans !='N'||ans !='n')
        {
            cout << "Please enter Y or y if you like to use the program again and N or n do exit.",
            cin >> ans; //If the question is asked and no matter what I input for ans, the while loop never gets exited. Why? Is there something I didn't use right?
        }
}while (ans == 'Y'||ans =='y');

return 0;

【问题讨论】:

    标签: while-loop inequality inequalities


    【解决方案1】:

    处理逻辑的更好方法是使用单个 do 循环,不断提示用户输入是/否,直到他给出:

    do {
        cout << "Please enter Y or y if you like to use the program again and N or n do exit.",
        cin >> ans;
    } while (ans != 'Y' || ans != 'y' || ans !='N' || ans !='n');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      相关资源
      最近更新 更多