Reputation: 103
Im trying to learn a bit about c++ and have run in to some trouble.
I have the following code:
char board[5][5];
ifstream myReadFile;
myReadFile.open("c:/test.txt");
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
while (myReadFile.good())
{
board[i][j] = myReadFile.get();
cout << board[i][j];
}
}
}
myReadFile.close();
for(int x=0; x<5; x++)
{
for(int y=0; y<5; y++)
{
cout << board[x][y];
}
cout << endl;
}
Now i was expecting the first loop to read the chars from the txt file and this works, so yeah! But the second loop, i was expecting to print the same char back to cout. However this was not the case, so i add the line
cout << board[i][j]
to the first loop to see if they where loading correctly. This is the result i get
(source: tbmilena.dk)
Can someone explain why the second loop isn't printing the same as the first.
Upvotes: 0
Views: 228
Reputation: 121427
you are replacing board[i][j] immediately after reading a char from file. Put the while loop as the outer most loop.
while (myReadFile.good())
{
board[i][j] = myReadFile.get();
cout << board[i][j];
}
Here, it continuously replaces board[i][j] with new character while i & j remains the same.
Upvotes: 4