如何让用户只输入一个字符
How to let users put in only one character?
所以我有一个基于文本的冒险游戏,它运行得很顺利,但我的一个"测试版"注意到,他可以在第一个cin位置选择多个数字,它会在游戏的其余部分使用这些值。我可以手动设置用户必须键入多少字符的块吗?这是我的程序
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstdlib>
char Choice;
char my_name;
using namespace std;
int main()
{
printf("You come out of darkness.n");
printf("Confused and tired, you walk to an abandoned house.n");
printf("You walk to the door.n");
printf("What do you do?n");
printf("1. Walk Away.n");
printf("2. Jump.n");
printf("3. Open Door.n");
printf(" n");
cin >> Choice;
printf(" n");
if(Choice == '1')
{
printf("The House seems too important to ignore.n");
printf("What do you do?n");
printf("1. Jump.n");
printf("2. Open Door.n");
printf(" n");
cin >> Choice;
printf(" n");
等等,你就可以得到它的要点
这在很大程度上依赖于平台,没有简单的包罗万象的解决方案,但一个有效的解决方案是使用std::getline
一次读取一行,忽略除第一个字符外的所有字符,或者在输入多个字符时抱怨。
string line; // Create a string to hold user input
getline(cin,line); // Read a single line from standard input
while(line.size() != 1)
{
cout<<"Please enter one single character!"<<endl;
getline(cin, line); // let the user try again.
}
Choice = line[0]; // get the first and only character of the input.
因此,如果用户输入更多或更少(较少为空字符串),将提示用户输入单个字符。
如果您希望玩家能够在不必按回车键的情况下按下1
、2
或3
等键,那么您很快就会进入特定于平台的代码。在Windows上,老派(我所说的老派,是指"可以追溯到80年代的DOS时代")控制台的方式是使用conio
例程。
不过,标准C++中并没有定义这种接口。
另一种方法是每次使用getline
获取整行的文本,然后丢弃第一个字符之后的所有内容。这将使您保持在普通C++中,并解决您的即时问题。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符