对于以下内容,我试图将用户输入限制为仅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;
答案 0 :(得分: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');