Reputation: 13
Hi guys im working on a school project which is an rpg game. I have created a load_game function which is supposed to go through a specific file, check if the file has the id the user enters and load that specific characters stats into global variables. The problem is that I made a function to print out the content of the file so the users can see their options but it doesnt print anything at all, I made a new_player function which fills the same file with new players and that works correctly. When i change a file to another one and write into that file manually it works. Here is the code:
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);
}
Upvotes: 0
Views: 51
Reputation: 409166
A major problem is that you open the same file twice. Once for input, and once for output which will truncate the file if it exists. So when you create out_stream
you will effectively remove all the data in the file.
If you want to read from and write to the same file either use std::iofstream
to open it in read/write mode. With text files it's hard to edit data in the file though, so I rather recommend you open a temporary file for the output, and when done you rename the temporary file as the actual file.
Or in your case, why have the output file at all? You don't actually use it anywhere? All it does is truncating the file you want to read.
Upvotes: 1