0

对于以下内容,我试图将用户输入限制为仅 Y 或 y 或 N 或 n。请遵循我对代码的评论,以便我指出问题所在。我是这个论坛的新手,我对编程充满热情,如果有人可以请帮助我。谢谢你。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;
4

1 回答 1

0

处理逻辑的更好方法是有一个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');
于 2016-04-01T11:04:34.003 回答