I've created a game that can save someone's game and then re-open that saved game for the next time you run the game. However, I'm trying to figure out how you would let the user input a username and save the file according to the username. It would need to be able to handle multiple users. The code I have for the input / output process is shown:
cout << "Would you like to save the game? (Y/N)" << endl;
cin >> YorN;
if (YorN == 'Y' || YorN == 'y')
{
cout << "Please enter a username: "<< endl;
cin >> Username;
OutData.open("username.txt");
if (!OutData)
{
cerr << "Your file could not be saved!" << endl;
}
else
{
OutData << Rounds;
for (int i = 0; i< ROWS; i++)
for (int j=0; j<COLUMNS; j++)
OutData << Board[i][j];
for (int k = 0; k < FIRSTLENGTH + 1; k++)
OutData << hitcount[k] << " ";
OutData.close();
}
if (!Din)
{
Clearboard(Board);
HitCounter(Board, hitcount);
}
else
{
cout << "Would you like to use your saved game? (Y/N) " << endl;
cin >> UseSave;
if (UseSave == 'Y' || UseSave == 'y')
{
cout << "Please enter your username exactly like you did when you saved it!" << endl;
cin >> Username;
Din >> Rounds;
for (int i = 0; i< ROWS; i++)
for (int j=0; j<COLUMNS; j++)
Din >> Board[i][j];
for (int k = 0; k < FIRSTLENGTH + 1; k++)
Din >> hitcount[k];
}
elseif (UseSave == 'N' || UseSave == 'n')
{
Clearboard(Board);
HitCounter(Board, hitcount);
}
else
{
cout <<"Since that was an invalid input, I assume you want to begin again! " << endl;
Clearboard(Board);
HitCounter(Board, hitcount);
}
}
Din.close();
You don't have to use string literals with fstream::open().
IE, you're doing this:
OutData.open("username.txt");
Since you're giving it "username.txt", it will always open a filename called "username.txt".
If you want to have a different file for each user, the files must have different names:
1 2 3 4 5 6 7
string username;
// <<get user name from user here>>
username += ".txt"; // add .txt to whatever the user's name is
OutData.open( username.c_str() ); // then use that string to open the file
So now if the user inputs "Dave", it will open "Dave.txt". And so on.