【问题标题】:How to let users put in only one character?如何让用户只输入一个字符?
【发布时间】:2013-11-27 14:37:49
【问题描述】:

所以我有一个基于文本的冒险游戏,它运行平稳,但我的一个“beta 测试人员”注意到他可以在第一个 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");

等等,你明白了它的要点

【问题讨论】:

    标签: c++ codeblocks


    【解决方案1】:

    这在很大程度上取决于平台,没有简单的包罗万象的解决方案,但一个可行的解决方案是使用 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.
    

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

    【讨论】:

      【解决方案2】:

      如果您希望播放器能够按下 123 等键而无需按 Enter,那么您很快就会进入特定于平台的代码。在 Windows 上,老派(我所说的老派,我的意思是“追溯到 80 年代的 DOS 时代”)控制台方式是使用 conio 例程。

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

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

      【讨论】:

      • 谢谢!但是 getline 会去哪里呢?在 cin 运算符下?
      • 这里是getline 的原始文档:en.cppreference.com/w/cpp/string/basic_string/getline 你需要做的是声明一个string 来捕获输入,然后查看字符串的第一位来确定什么玩家选择。您最好将其分解为专用函数。
      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多