所以我有一个基于文本的冒险游戏并且它运行顺利,但我的一个“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");
等等,你得到了它的要点
答案 0 :(得分:3)
这在很大程度上依赖于平台,并没有简单的全能解决方案,但一个有效的解决方案是使用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)
如果您希望玩家能够按下1
,2
或3
这样的按键而无需按Enter键,那么您很快就会进入特定于平台的代码。在Windows上,旧学校(以及老派,我的意思是“追溯到80年代的DOS时代”)控制台方式是conio
例程。
但标准C ++中没有任何内容可以定义那种接口。
另一种方法是每次使用getline
获取整行的文本,然后丢弃第一个字符后的所有内容。这将使你在普通的C ++中,并解决你的直接问题。