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條件也是錯誤的,它應該是&&。請參閱下面的答案。 –