如何停止对输入的每个字符重复输入
How can I stop input repeating for each char inputted?
我正在尝试编写一个提示,要求用户确认操作,其中 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;
}
相关文章:
- 无法在 C++ 中输入字符数组
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 在不使用字符串库的情况下输入字符*
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- C++中输入字符数组的特定验证
- 如果用户在 int 中输入字符,如何使用输入
- 当我们在以下程序(C )中输入字符时,该如何解决
- 如何在结构中输入字符到向量
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 输入字符时忽略回车键
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- 如何在应该显示的printf之前输入字符
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 为什么"keep_window_open()"不等待输入字符?
- 为什么我的程序在输入字符时有一个无限循环
- 当提示输入整数值时输入字符时,为什么程序会中断
- 关闭回显后如何再次回显输入字符
- 忽略输入字符
- 从文件的单行读取输入字符