我不明白为什么这个函数不起作用

I don't understand why this function isn't working

本文关键字:函数 不起作用 为什么 明白      更新时间:2023-10-16

这是我正在创造的一款简单的基于文本的游戏,从菜单开始。我希望人们能够在按下'p'时玩游戏,但这个游戏功能不起作用。

#include <iostream>
#include <string>
using namespace std;
void menu()
{
char menuResponse;
cout << "[P]lay [O]ptions [C]reditsn";
cin >> menuResponse;
if (menuResponse == 'p')
{
    game();
}
else if (menuResponse == 'o')
{
    cout << "There's actually nothing to see here, sorry.n";
    char optionResponse;
    cout << "[B]ackn";
    cin >> optionResponse;
    menu();
}
else if (menuResponse == 'c')
{
    cout << "Created by Crusader Studios, 2014n";
    char creditResponse;
    cout << "[B]ackn";
    cin >> creditResponse;
    menu();
}
else
{
    cout << "Please type a valid letter.n";
    menu();
}
}
void game()
{
    cout << "tttProloguenn";
}
int main()
{
    cout << "ttWelcome to my first game, 'A Hero's Journey!'nn";
    cout << "To navigate through menus, type the letters inside the brackets. For            example,n";
    cout << "pressing 'p' in a menu with [P]lay and [O]ptions will let you play.nn";
    char beginResponse;
    cout << "Do you understand? If so, press any key:n";
    cin >> beginResponse;
    cout << "Great! Now we can begin our game!n";
    menu();
    return 0;
}

游戏函数为void game(),菜单为void menu()。

您还没有声明函数…

void game();

void menu()函数前声明

void game();
void menu()
{
//... code
}

你需要在使用它之前给出函数的原型,因此我们需要在C/c++中主要使用头文件。

所以在使用之前,if (menuResponse == 'p'){游戏();}

你应该声明prototype。

void game();
....
if (menuResponse == 'p')
{
    game();
}