gpt4 book ai didi

c++ - 限制用户输入

转载 作者:行者123 更新时间:2023-11-28 06:49:58 25 4
gpt4 key购买 nike

我已经编写了以下代码,并且在很大程度上它完成了我想要它做的事情。问题在于,当用户输入“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){
...

关于c++ - 限制用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24150413/

25 4 0
文章推荐: c++ - cpp : delete folder open by others
文章推荐: javascript - 在数据列表内切换 Div 标签
文章推荐: javascript - 在 Google Chrome 中使用 JavaScript 从