如何让用户只输入一个字符

How to let users put in only one character?

本文关键字:一个 字符 输入 用户      更新时间:2023-10-16

所以我有一个基于文本的冒险游戏,它运行得很顺利,但我的一个"测试版"注意到,他可以在第一个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.

因此,如果用户输入更多或更少(较少为空字符串),将提示用户输入单个字符。

如果您希望玩家能够在不必按回车键的情况下按下123等键,那么您很快就会进入特定于平台的代码。在Windows上,老派(我所说的老派,是指"可以追溯到80年代的DOS时代")控制台的方式是使用conio例程。

不过,标准C++中并没有定义这种接口。

另一种方法是每次使用getline获取整行的文本,然后丢弃第一个字符之后的所有内容。这将使您保持在普通C++中,并解决您的即时问题。

相关文章: