2017-03-23 130 views
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: 

我在做什麼錯了?

+0

無關的問題,但是,在什麼情況下,你希望'而(結果=「Y」 ||導致=「N ')'終止?在表達式中,唯一可能的值組合就是結果爲'假'(即退出循環)的結果是'result'等於'y'',而'n'' * *與此同時**。這是不可能的。 –

+0

是的,我意識到我的II條件也是錯誤的,它應該是&&。請參閱下面的答案。 –

回答

0

所以如果我的輸入被存儲爲一個字符串(而不是字符),我不會得到每個字符輸入的重複。另外,我的while循環的條件應該是和而不是OR:!

string result = ""; 

while (result != "y" && result != "n") 
{ 
    cout << "Do you wish to continue & overwrite the file? Y/N: "; 
    cin >> result; 
    transform(result.begin(), result.end(), result.begin(), ::tolower); 
} 

if (result == "y") 
{ 
    cout << "YES!" << endl; 
} 
else if (result == "n") 
{ 
    cout << "NO!" << endl; 
} 
+0

字符串的典型默認初始化將是一個空字符串,'string result =「」;'。確保不要將字符串視爲字符。不過,你的代碼仍然可以正常工作。 – Aziuth