如何防止用户在下面的示例代码中输入多个字符
How to prevent the user from entering more than one character in the below sample code?
我在下面的代码中遇到了问题。如果用户输入了多个字符,那么我的循环执行的次数等于用户输入的字符串的长度。我的代码是用GNU c/c++编译器编写的。
提前谢谢。
int continue_option()
{
char c;
loop:
fflush(stdin);
cin.ignore();
cout<<"nnttttPress (Y/y) - Continue / Press (N/n) - Exit :";
cin>>c;
if(c=='y'||c=='Y')
{
system("clear");
}
else if(c=='n'|| c=='N')
{
exit(0);
}
else
{
printf("nttttInvalid Option.Try Again.....");
goto loop;
}
fflush(stdin);
}
首先,不要使用跳转。它们是老式的,让Dijkstra在坟墓里旋转,再加上所有其他的不良后果。我的意思不是"复古",我的意思是旧的。
至于你的问题,我宁愿把结果放在std::字符串中,只考虑其中的第一个字符:
std::string input;
std::cin >> input;
switch (input[0]) {
case 'y':
case 'Y':
//your code
break;
case 'n':
case 'N':
exit(0);
default:
std::cout << "Invalid text" << std::endl;
}
我也不会使用exit(),我宁愿依赖函数的返回值来最终导致返回0;在main()中,或者一些等效的技术。
您无法阻止用户键入多个字符。
你能做的就是忽略行的其余部分。您已经使用了忽略一个字符的cin.ignore()
。您可以使用cin.ignore(large number)
忽略大数字或行尾,以先出现的为准。
与刷新输出文件不同,fflush(stdin)
实际上什么都不做。
尝试使用cin.get()
或getch()
一次只读取一个字符。此外,我想你最好用一个简单的循环来代替整个过程,比如:
char ch = ' ';
do
{
ch = getch();
}while((tolower(ch) != 'y') || (tolower(ch) != 'n'))
if(tolower(ch) == 'y')
{
//additional handling
}
else
{
exit(0);
}
不是完全相同的行为,但应该会让你走上正轨:
#include <iostream>
#include <iomanip>
bool is_valid_answer(char c)
{
switch(c)
{
case 'y':
case 'Y':
case 'n':
case 'N':
return true;
default:
return false;
}
}
bool continue_option()
{
std::cout << "Press (Y/y) to continue, (N/n) to exit: " << std::flush;
char c = ' ';
while (std::cin.get(c) && !is_valid_answer(c));
return ((c == 'y') || (c == 'Y'));
}
int main()
{
std::cout << "Continue option: " << continue_option() << std::endl;
}
相关文章:
- 无法在 C++ 中输入字符数组
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 在不使用字符串库的情况下输入字符*
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- C++中输入字符数组的特定验证
- 如果用户在 int 中输入字符,如何使用输入
- 当我们在以下程序(C )中输入字符时,该如何解决
- 如何在结构中输入字符到向量
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 输入字符时忽略回车键
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- 如何在应该显示的printf之前输入字符
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 为什么"keep_window_open()"不等待输入字符?
- 为什么我的程序在输入字符时有一个无限循环
- 当提示输入整数值时输入字符时,为什么程序会中断
- 关闭回显后如何再次回显输入字符
- 忽略输入字符
- 从文件的单行读取输入字符