gpt4 book ai didi

c++ - 在 C++ 中包含 .txt 文件中的文本以获得学分的问题

转载 作者:行者123 更新时间:2023-11-27 23:25:57 25 4
gpt4 key购买 nike

我一直在为我的文字冒险游戏开发一个主菜单(我用它来学习,而不是发布它),但我遇到了一个大问题。主菜单有播放、显示演职员表和终止程序三个选项。第二个选项,显示演职员表,需要从 credits.txt 中获取信息并将其发布在屏幕上,在用户按下按钮后,将用户带回主菜单。主菜单构建为头文件 (menu.h),主游戏位于 test_project.cpp 中。我将在这里给出完整的 menu.h 和一部分 .cpp,当然还有错误:


菜单.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

测试项目.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;

这里是错误:

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

最佳答案

尝试将案例 2 重写为:

case 2:{
ifstream creditsFile("credits.txt");
while ( !creditsFile.eof() ){
string readLine;
getline(creditsFile, readLine);
cout << readLine;
}
creditsFile.close();
break;
}

编辑

用这个替换 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

关于c++ - 在 C++ 中包含 .txt 文件中的文本以获得学分的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9534333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com