限制用户输入
Limiting user input
我已经编写了以下代码,并且在很大程度上它做了我想要它做的事情。问题是,当用户输入"111"之类的东西时,输出是"您输入了数字1"。我想将用户的输入限制为1个字符。有什么建议吗?我相信解决办法很简单,但是我想不出来。此外,代码必须保持switch语句的形式。谢谢你!
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Please enter a number between 1 and 9." << endl;
cout << "Enter a number: ";
cin >> i;
switch (i)
{
case '1':
cout << "You entered the number one." << endl;
break;
case '2':
cout << "You entered the number two." << endl;
break;
case '3':
cout << "You entered the number three." << endl;
break;
case '4':
cout << "You entered the number four." << endl;
break;
case '5':
cout << "You entered the number five." << endl;
break;
case '6':
cout << "You entered the number six." << endl;
break;
case '7':
cout << "You entered the number seven." << endl;
break;
case '8':
cout << "You entered the number eight." << endl;
break;
case '9':
cout << "You entered the number nine." << endl;
break;
default:
cout << "You did not enter a valid number." << endl;
break;
}
system("pause");
return 0;
}
您可以使用c标准io库中的getchar(char)。
#include <stdio.h>
...
char i;
int j;
cout << "Please enter a number between 1 and 9." << endl;
cout << "Enter a number: ";
getchar(j);
i=(char)j;
switch(i){
...
有一种方法很容易:只需将char c
切换到int n
,并将case '1'
替换为case 1
等。尝试这样做,直到用户输入一个有效的数字,然后输入"a"(即不是数字的东西)。通常,容易的方式也是错误的方式。;)
现在,你可以用这段代码来代替:
std::string line;
while (getline(std::cin, line))
{
if (line == "1") {
std::cout << "You entered the number one." << std::endl;
} else if (line == "2") {
// ....
} else {
std::cout << "You didn't enter a valid number" << std::endl;
}
}
这里的不同之处在于,由于输入是行基的,没有进一步的解释,所以当输入不能被解释为数字时,流状态不会被修改。在与用户交互时,这通常更健壮。如果稍后您希望使用数字,请查看stringstreams或lexical_cast进行转换。
您可以使用getch()从屏幕上获取单个字符,您可以检查它是否为数字,否则再次请求有效输入
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 用户定义函数中的指针和输入
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 为什么在代码块中执行时会跳过输入用户输入的行?
- 使用 for 循环在数组中输入用户