所以我有一个基于文本的Adventure Game,它运行平稳,但是我的一个“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.
因此,如果他们输入的字符更多或更少(不是空字符串),将提示用户输入单个字符。