gpt4 book ai didi

c++ - 如何从文本文件中填充指针数组?

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:13 25 4
gpt4 key购买 nike

我正在处理一个今天到期的学校项目,但我遇到了一个可能很简单的问题。

我需要制作“Hangman”游戏,我遇到的任务是从文本文件中填充指针数组(我需要阅读图片以获取错误答案)。

void ReadScenes(string *scenes[10])
{
ifstream inFile("Scenes.txt");
if (inFile.is_open())
{
int i = 0;
string scene;
while ((inFile >> scene)&&(i<10))
{
*scenes[i] = scene;
i++;
}
}
}
int main()
{
char *scenes[10];
ReadScenes(scenes);
}

我的文本文件如下所示:

char *scene1 =
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" * \n"
" * * \n"
" * * \n";


char *scene2 =
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * * \n"
" * * \n";

等等。

方法中的代码用于读取密码,因为它们是用空格分隔的。所以我有 10 个场景,我想将它们保存在数组中。

最佳答案

一个问题是您认为您读取的文件应该是具有变量声明的类 C++ 文件。它不是这样工作的。

您应该将文件的内容放入普通的 C++ 源文件中并使用它进行构建。

有点像

std::string scenes[] = {
// Scene 1
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" * \n"
" * * \n"
" * * \n",

// Scene 2
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * \n"
" * * \n"
" * * \n",

// And so on...
};

如果您使用 IDE,请将源文件添加到您的项目中。

如果您使用例如g++ 然后在命令行上构建

g++ -Wall main.cpp scenes.cpp -o my_program

其中 scenes.cpp 是包含 scenes 数组的源文件。


如果您需要使用外部文本文件,而无需任何 C++ 代码,那么实际上非常简单:只需按原样存储文本,不带引号或任何类似 C++ 声明或语句的内容。

因为您知道每个“场景”恰好是九行(可能还有一行用于分隔两个场景),所以您使用 for 循环来读取该行。

所以你的文本文件看起来像

           *                        * *                      *   *                       *                         *                         *                         *                         *                         *                         *                        * *                      *   *            

Then to load it

constexpr size_t NUMBER_OF_SCENES = 2;  // With the example scene file in this answer
constexpr size_t LINES_PER_SCENE = 9;

std::ifstream scene_file("scenes.txt");

std::array<std::string, NUMBER_OF_SCENES> scenes;

// Loop to read all scenes
for (std::string& scene : scenes)
{
std::string line;

// Loop to read all lines for a single scene
for (unsigned line_number = 0; line_number < LINES_PER_SCENE && std::getline(scene_file, line); ++line_number)
{
// Add line to the current scene
scene += line + '\n';
}

// Read the empty line between scenes
// Don't care about errors here
std::getline(scene_file, line);
}

关于c++ - 如何从文本文件中填充指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54180275/

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