In my code I have two functions, Save
and Load
file, which operate on an array called Players
.
The array Players
is defined in a second file, along with some other variables. Lastly, I have a main file with the main function.
In the main function, I call Load
, which writes player names from a file into the array Players
.
When I then attempt to output the Players
with cout
, all of them are empty, even though between the call to Load
and the cout
statements in main
, I do nothing.
When I print Players
in the Load
function, the names are printed as expected.
So, seems that the contents of Players
gets deleted when I use it in the main function.
The Load Function:
void Load() {
std::string line;
std::ifstream LoadStream;
LoadStream.open(PlayersFilePath);
if (LoadStream.is_open()) {
for (int i = 0; i < MaxPlayers; i++) {
std::getline(LoadStream, line);
Players[i] = line;
}
return;
}
else {
std::cout << Error1 << PlayersFilePath << std::endl;
exit(0);
}
}
Here is the Variable File with the Players Array:
#include <string>
using namespace std;
static const int MaxPlayers = 10;
static int ActivePlayers;
static int ActivePlayerIndex1, ActivePlayerIndex2, ActivePlayerIndex3, ActivePlayerIndex4, ActivePlayerIndex5, ActivePlayerIndex6, ActivePlayerIndex7, ActivePlayerIndex8, ActivePlayerIndex9, ActivePlayerIndex10;
static int counter;
static const string Error1 = "File could not be found or opened. File: ";
static const string Error2 = "Saving Error";
static const string PlayersFilePath = "C:\\Users\\Felix\\source\\repos\\ClassTraining\\Players.txt";
static string Players[MaxPlayers];
static const string German = "Deutsch";
static const string English = "English";
And here is the Main Function:
#include <iostream>
#include <string>
#include "Variables.cpp"
#include "SaveLoad.h"
int main() {
Load();
for (int i = 0; i < MaxPlayers; i++) {
std::cout << Players[i] << std::endl;
}
return 0;
}