0
我想写一个提示,要求用户确认一个操作,只有两个选项是Y/N。如何停止输入每个字符的重复输入?
如果用户输入Y,它会执行某些操作,如果用户输入N,则它执行其他操作。但是,如果用户输入除Y或N以外的任何东西,则只需重复该问题,直到按下Y或N。
这是我到目前为止有:
char result = '\0';
while (result != 'y' || result != 'n')
{
char key = '\0';
cout << "Do you wish to continue & overwrite the file? Y/N: ";
cin >> key;
result = tolower(key);
}
if (result == 'y')
{
cout << "YES!" << endl;
}
else if (result == 'n')
{
cout << "NO!" << endl;
}
而我的问题是,如果我输入多个无效字符,它再次显示提示每个无效字符,像这样:
Do you wish to continue & overwrite the file? Y/N: abc
a
Do you wish to continue & overwrite the file? Y/N: b
Do you wish to continue & overwrite the file? Y/N: c
Do you wish to continue & overwrite the file? Y/N:
我在做什么错了?
无关的问题,但是,在什么情况下,你希望'而(结果=“Y” ||导致=“N ')'终止?在表达式中,唯一可能的值组合就是结果为'假'(即退出循环)的结果是'result'等于'y'',而'n'' * *与此同时**。这是不可能的。 –
是的,我意识到我的II条件也是错误的,它应该是&&。请参阅下面的答案。 –