大家好,我正在一个rpg游戏的学校项目中工作。我创建了一个load_game函数,该函数应该通过特定的文件,检查文件是否具有用户输入的ID,并将特定的字符统计信息加载到全局变量中。问题是我制作了一个函数来打印文件的内容,以便用户可以看到他们的选项,但是根本不打印任何内容,我制作了一个new_player函数,该函数用新的播放器填充相同的文件,并且可以正常工作。当我将文件更改为另一个文件并手动写入该文件时,它将起作用。这是代码:
void load_game()
{
bool loading = true;
do{
ifstream in_stream("Players.txt");
ofstream out_stream("Players.txt");
cout << " The last son of Allheaven " << endl;
cout << "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+" << endl;
char ch;
in_stream.clear();
in_stream.seekg(0, in_stream.beg);
while (in_stream.get(ch))
{
cout << ch;
}
cout << " Enter -1 to return to main menu " << endl;
cout << "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+" << endl;
cout << endl << "Enter a number to access one of the above options: ";
in_stream.clear();
in_stream.seekg(0, in_stream.beg);
int choice;
cin >> choice;
while (in_stream >> ID >> Name >> Class >> HP >> Mana >> ATK >> ability_dmg >> Defense >> magic_resist >> player_exp >> player_level)
{
if (choice == ID)
{
/*game_start();*/
loading = false;
break;
}
else if (choice == -1)
{
system("cls");
main_menu();
}
else if (in_stream.eof())
{
in_stream.clear();
in_stream.seekg(0, in_stream.beg);
cout << endl << "Error! Invalid ID !" << endl;
}
}
in_stream.close();
out_stream.close();
} while (loading);
}
一个主要的问题是您两次打开相同的文件。一次用于输入,一次用于输出,这将截断文件(如果存在)。因此,在创建时,out_stream
您将有效地删除文件中的所有数据。
如果要读取和写入同一文件,请使用std::iofstream
,以读/写模式将其打开。但是对于文本文件而言,很难在文件中编辑数据,因此我建议您为输出打开一个临时文件,并在完成后将临时文件重命名为实际文件。
或者在您的情况下,为什么根本没有输出文件?您实际上不在任何地方使用它吗?它所做的只是截断您要读取的文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句