c++ - 如何让用户只输入一个字符?

标签 c++ codeblocks

所以我有一个基于文本的冒险游戏并且运行顺利,但我的一个“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");

等等,你就明白了

最佳答案

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

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

关于c++ - 如何让用户只输入一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20245276/

相关文章:

c++ - 如何让自定义(计时)计时器与 sleep_until 一起工作?

c - 如何在 C 中使用 PlaySound

C++ "OR"运算符

c++ - Void 类型函数不打印出结构成员变量

c - 函数声明符代码块之后的预期函数体

C++: "multiple definition of ' mainCRTStartup' "错误等

c++ - Qt 库中控件的默认 HTML 样式

c++ - 链表数组大小不同

使用 Boost Regex 的 C++ 正则表达式

c++ - 添加到结构 vector 时出现 Stanford CS 106B 错误 — 编译器问题?