我知道这可能看起来像一个简单的问题,但我有一个课程作业来制作一个20问题类型的游戏。我以为我会多做一些菜单。该程序运行正常,但当我输入实际的游戏文件时,它输出第一行然后转到我的最后一个其他输出...它不会让我输入和玩游戏。这很容易解决吗?
当我启动程序时,菜单会按原样运行。它提示用户输入导航(1 =玩游戏,2 =指令,3 =单词数据库,4 =退出)。当我按1来支付游戏时,它会像它应该的那样清除屏幕,但不是让我输入我对第一个问题(动物,食物,元素,其他)的回答,它说"它是动物,食物,元素或其他? (输入a,f,e或o进行选择)",就像它应该的那样,但接着我输入的1并将其用作此问题的输入,使其输出"那&#39 ;不是一种选择!"在提示输入关闭程序之前。我怎样才能解决这个问题?我并不热衷于包含所有代码,因为它长达几百行,但这是我的菜单文件,头文件和游戏文件的开头:
myheader.h:
#include <windows.h>
#include <iostream>
void runGame();
void showHowTo();
void showWords();
void mainMenu();
menu.cpp:
#include <iostream>
#include <string>
#include "myheader.h"
#include <windows.h>
using namespace std;
int main()
{
int x = 0;
cout << "*******************************\n";
cout << "*****20 QUESTIONS**************\n";
cout << "*******************************\n\n";
cout << "Press a key to make a selection.\n\n\n";
cout << "1: Play Game" << endl;
cout << "2: View Instructions" << endl;
cout << "3: View Word Database" << endl;
cout << "4: Close Window\n\n\n";
cin >> x;
if (x == 1)
{
system("cls");
runGame();
}
else if (x == 2)
{
//instructions function would be here, but was removed as it is not relevant to my question
}
else if (x == 3)
{
//word database function would be here, but was removed as it is not relevant to my question
}
else if (x == 4)
{
system("pause");
return 0;
}
system("pause");
return 0;
}
game.cpp:
#include <iostream>
#include <string>
#include "myheader.h"
#include <windows.h>
using namespace std;
void runGame()
{
//declaring variables
string userInput = "";
bool no = ((userInput == "no") || (userInput == "No") || (userInput == "NO") || (userInput == "nO"));
string disappointment = "Awww... Oh well, maybe I'll get it next time!\n";
string excitement = "Yay! I feel smart!\n";
bool animal = ((userInput == "A") || (userInput == "a"));
bool food = (userInput == "F" || userInput == "f");
bool element = (userInput == "E" || userInput == "e");
bool other = (userInput == "O" || userInput == "o");
// Prompt user for input (animal, vitamin, element, or other
cout << "Welcome to 20 Questions!\nPlease think of something, and answer the questions honestly!\n\n";
cout << "Is your object an animal, vitamin, element, or other? (Please answer A, F, E, or O)\n";
getline(cin,userInput);
animal = ((userInput == "A") || (userInput == "a"));
food = (userInput == "F" || userInput == "f");
element = (userInput == "E" || userInput == "e");
other = (userInput == "O" || userInput == "o");
if (animal)
{
//full game in here
}
else
{
cout << "That's not an option!\n";
}
system("pause");
}
这些是我挣扎的代码文件......请不要指出系统(&#34;暂停&#34;)效率不高,我已经知道了。我只需要知道如何在游戏开始运行时让我的用户输入正常工作。如果我的描述很糟糕,这些是我输出的照片。
菜单:
游戏
请帮忙!我明天需要这个工作,而且我被卡住了!
编辑:感谢@ThomasMatthews !!! 我通过put getline(cin,userInput)修复它;两次一个在另一个之上。不知道为什么会有效,但确实如此!我的程序运行正常!谢谢!!!!答案 0 :(得分:1)
因为你做cin&gt;&gt; x你STDIN实际上在缓冲区中有一个额外的字符(当你按回车时换行)
因此,你的getline(...)实际上是获取缓冲区中已有的回车键。
您可以通过执行cin.ignore()来解决此问题。预先,或使用getline(...)代替cin&gt;&gt; X