2017-03-23 132 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