如何停止对输入的每个字符重复输入

How can I stop input repeating for each char inputted?

本文关键字:输入 字符 何停止      更新时间:2023-10-16

我正在尝试编写一个提示,要求用户确认操作,其中 Y/N 是仅有的两个选项。

如果用户输入

Y,它会执行某些操作,如果用户输入 N,它将执行其他操作。但是,如果用户输入 Y 或 N 以外的任何内容,它只会重复问题,直到按下 Y 或 N。

这是我到目前为止得到的:

char result = '';
while (result != 'y' || result != 'n')
{
  char key = '';
  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: 

我做错了什么?

因此,如果我的输入存储为字符串(而不是字符(,我不会得到每个输入的字符的重复。另外,我的while循环条件应该是AND而不是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;
}