I’ve been working on a main menu to use for my text-adventure game (which I use to learn, not to publish it), but I’m having a big problem with it. The main menu has three options, play, show the credits and terminate the program. The second option, showing the credits, needs to get the information out of credits.txt and publish this in the screen, and after the user presses a button, bring the user back to the main menu. The main menu is build as a header file (menu.h) and the main game is in test_project.cpp. I will give the full menu.h and a part of the .cpp here, plus the error of course:
Menu.h:
#ifndef MENU_H
#define MENU_H
void displayMenu () {
int menuItem;
bool menuRunning = true;
while ( menuRunning ) {
cout << "Choose a menu item:\n";
cout << "1. Play\n2. Credits\n3. Exit\n";
cin >> menuItem;
switch ( menuItem ) {
case 1:
menuRunning = false;
break;
case 2:
ifstream creditsFile("credits.txt");
while ( !creditsFile.eof() )
{
string readLine;
getline(creditsFile, readLine);
cout << readLine;
}
creditsFile.close();
break;
case 3:
menuRunning = false;
exit(0);
default:
cout << "";
}
cout << "\n---\n";
}
}
#endif
Test_project.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
using namespace std;
#include "menu.h"
int main()
{
displayMenu(); // This is where the functions from menu.h must be loaded, before the actual game starts.
system("TITLE Title of the program comes here");
// This is where the game starts, which loads when the user presses 1.
int ab, cd;
And here is the error:
menu.h: In function `void displayMenu()':
In file included from test_project.cpp:11:
menu.h:29: error: jump to case label
menu.h:20: error: crosses initialization of `std::ifstream creditsFile'
menu.h:32: error: jump to case label
menu.h:20: error: crosses initialization of `std::ifstream creditsFile'
menu.h:29: warning: destructor needed for `creditsFile'
menu.h:29: warning: where case label appears here
menu.h:29: warning: (enclose actions of previous case statements requiring destructors in their own scope.)
menu.h:32: warning: destructor needed for `creditsFile'
menu.h:32: warning: where case label appears here
In file included from test_project.cpp:11:
menu.h:40:7: warning: no newline at end of file
try to rewrite case 2 as:
Edit
replace content of Menu.h with this: