Hi, I'm trying to create a series of functions that will allow me to create and load save games. My first issue is that I need to be able to check which save files already exist.
1 2 3 4 5 6
|
int gameSaveCheck()
{
int gsx = 1;
int gsy = 0;
std::cout<<"Checking save files...\n";
|
This is where I'm initializing the function and placing two starting variables. One is "gsx" which I will be using in my loop. "gsy" will receive the value of gsx when my checks are complete.
Please ignore that I am using a goto loop setup when I could do it much easier with a "for" loop. I will fix that later...
1 2 3 4 5 6 7 8 9 10 11 12
|
loopStart:
std::ifstream myfile("gameSave" +gsx + ".txt");
if (myfile.good()) {myfile.close();gsx++; goto loopStart;}
else gsy = gsx;
if (gsy == 0) std::cout<<"Error, gsy came out 0";
else if (gsy > 10) std::cout<<"You already have 10 saved games. Please delete one.";
else if (gsy < 10) std::cout<<"This will be save number "<<gsy;
return (gsy);
|
So i'm trying to use the following to check if the file exists.
if (myfile.good())
Here's my problem. I want this function to run a search for a file named "GameSave1.txt" and if it exists I would like it to then run a check on "GameSave2.txt", and then "GameSave3.txt" and so on and so on.
Using the function;
std::ifstream myfile("example.txt");
How can i write it out so that "example.txt" can be changed through each iteration of a loop?
I thought the answer would be simple by using either;
std::ifstream myfile ("GameSave"+Variable+".txt")
or
std::ifstream myfile ("GameSave"Variable".txt")
Neither of these worked.
My next attempt was trying to create the string content outside of the check like so...
1 2
|
std::string gameSav = "GameSave" + variable + ".txt";
std::ifstream myfile (gameSav);
|
Although I can get this to send out the correct string when I output the string variable itself, I cannot get it to work inside the ifstream function.
I last tried using stringstream. However, it seems that the ifstream function will only accept a direct string, not a variable to a string.
Here's what I tried;
1 2 3
|
std::stringstream gameSav;
gameSav<<"GameSave"<<gsx<<".txt";
std::string gameSave = gameSav;
|
any suggestions besides changing the loop to a for loop? (I assume that it is not the reason i'm having this problem even though it's bad practice).
If it's impossible to do what I'm trying to do with the ifstream function, please explain why and perhaps a better solution to checking the existence of txt files in a looping formation.