Trying to make a Spanish-English dictionary. I'm writing strings (for the words) and ints (for a "times word searched" feature) into a file, reading them into parallel arrays, and displaying those arrays to make sure they're reading correctly.
File data reads into arrays and prints to console fine, except when it breaks out of the for
loops, it evaluates !EOF
as still true and repeats the while
loop one more time.
This is what the code looks like now:
// GLOBAL CONSTS
const int ENG_WORDS = 3, SPN_WORDS = 2, SIZE = 3;
// MAIN
string words[ENG_WORDS][SPN_WORDS]; int searches[SIZE];
ofstream outFile; ifstream inFile;
// FILE WRITE
outFile.open("test.txt");
outFile << "hello, hola, 0" << endl <<
"bye, adios, 0" << endl <<
"thanks, gracias, 0" << endl;
outFile.close();
// FILE READ
inFile.open("test.txt");
while (!inFile.eof())
{
for (int r = 0; r < ENG_WORDS; r++)
{
for (int c = 0; c < SPN_WORDS; c++)
{
inFile >> words[r][c];
cout << words[r][c] << " ";
if (words[r][c] == words[r][SPN_WORDS - 1])
{
inFile >> searches[r];
cout << searches[r] << "\n";
}
}
}
}
inFile.close();
Output:
hello, hola, 0
bye, adios, 0
thanks, gracias, 0
hello, hola, 0
bye, adios, 0
thanks, gracias, 0
This is the mess I had before attempting to debug:
// FILE READ
inFile.open("test.txt");
while (!inFile.eof()) {
for (int r = 0; r < ENG_WORDS; r++)
{
for (int c = 0; c < SPN_WORDS; c++)
{
inFile >> words[r][c];
cout << words[r][c] << " ";
if (words[r][c] == words[r][SPN_WORDS])
{
inFile >> searches[r];
cout << searches[r] << endl;
}
}
}
}
Output when ENG_WORDS = 3, SPN_WORDS = 3
:
hello, hola, 0 bye, adios, 0 thanks, gracias, 0 hello, hola, 0 bye, adios, 0 thanks, gracias, 0
Output when ENG_WORDS = 3, SPN_WORDS = 2
:
hello, hola, 0 bye, adios, 0 thanks, gracias, 0 bye, adios, 0
Output when ENG_WORDS = 2, SPN_WORDS = 2
:
0, bye, adios, 0 0 (infinite loop)
I assumed EOF was evaluating to true because the row size was too small to hold all of the rows in the file. While the output was more or less in the right order, it was actually overwriting the array before. (Array singular, since the if
was just being skipped over and the 3x3 string array was holding the 0s.) Funnily enough, when ENG_WORDS = 3
and SPN_WORDS = 2
, it only repeats the second row, instead of all three.
Also, if I put \n
in the file write, the file never reads into the array but always executes the if
statement, displaying garbage values in searches[r]
. This is why I'm using endl
, but if there's a way around that I'd love to know.