DomainFlag
DomainFlag

Reputation: 564

Create a text file with data if there isn't, and read it afterwards to retrieve data

I need for a project to save the progress of the user playing the game. I have the code that creates the file if there isn't and gives it starting values, and the other that reads the file both when it existed before or newly created. The 2 parts work all by themselves but when together it gives an error.(redeclaration of ifstream myfile)

#include <fstream>
#include <string.h>

int i = 0;
string line;

ifstream myfile ("progress.txt");
if(!myfile)
{
    ofstream myfile;
    myfile.open ("progress.txt"); //create new file
    myfile << "0\n";
    myfile << "1\n";
    myfile << "1\n";
}

ifstream myfile;
while(getline(myfile, line))
{
    WL.levels[i].lockedLevel = line[0];
    i++;
}
myfile.close();

Any suggestions to make it work?

Upvotes: 1

Views: 60

Answers (1)

SimoV8
SimoV8

Reputation: 1402

Yes, in fact you are declaring two times myfile that gives a compilation error. A quick fix would be to create another stream with a different name or better close and reopen it:

myfile.close();
myfile.open("progress.txt");

that you have to put instead of the second ifstream myfile; line.

However, you don't really need to close the stream and reopen it, a still better solution would be to just reset the position of the next character to read to zero with seekg method:

myfile.seekg(0);

Update: I didn't see at the beginning you also created an ofstream object with the same name inside the if statement. If you want to both read and write the file you should consider to define myfile as fstream only once, at the beginning, and then use seekg to reset the position after the writing.

Upvotes: 1

Related Questions