For this task, I am opening a text file and trying to read lines 1 and 3 into the array named front (at indices 0 and 1 respectively), and then read lines 2 and 4 into the array named back (at indices 0 and 1 respectively), but it's not quite doing it. Nothing is getting inputted into the arrays, my loop logic must be off. I want to read each line as is (with spaces included) up until the newline character. Any help is appreciated.
void initialize(string front[], string back[], ifstream &inFile)
{
string fileName = "DevDeck.txt"; //Filename
string line;
inFile.open(fileName); //Open filename
if (!inFile)
{
cout << "Couldn't open the file" << endl;
exit(1);
}
//Create the parallel arrays
while (!inFile.eof())
{
for (int index = 0; index < 4; index++)
{
getline(inFile, line);
front[index] = line; //Store in first array
getline(inFile, line);
back[index] = line; //Store in second array
}
}
}
Your loop for (int index = 0; index < 4; index++)
has the wrong condition since you want 4 strings in total but in each loop you get 2 so right now you would get 8 strings.
I tried to run your code with that change like this:
int main()
{
string front[2];
string back[2];
ifstream inFile;
initialize(front, back, inFile);
cout << front[0] << endl << back[0] << endl << front[1] << endl << back[1];
return 0;
}
and it worked perfectly for me. It displayed:
line1
line2
line3
line4
In order to help you further you should provide the DevDeck.txt
file and the piece of code that calls this function.