I'm reading the contents of a .txt file into an array of char arrays. For some reason I'm getting a duplicate on the last entry, can anyone shed some light on this?
usingnamespace std;
#include <iostream>
#include <fstream>
int main()
{
char food[4][10] = {' '};
char buffer[10];
ifstream iFile("food.txt");
iFile.close();
ofstream oFile("food.txt");
oFile << "Candy" << endl << "turkey" << endl << "steak" << endl << "potatoes" << endl;
oFile.close();
// Up to here, everything's hunky dory, when I try to read into the char array
// is where I'm just plain stuck.
iFile.open("food.txt");
int r = 0;
int c = 0;
while(!iFile.eof())
{
if(iFile.eof()) break;
iFile >> buffer;
c = 0;
while(buffer[c] != '\0')
{
food[r][c] = buffer[c];
food[r][c + 1] = '\0';
c++;
}
r++;
}
for(int i = 0; i < 4; i++)
{
cout << food[i] << endl;
}
ofstream oFood("oFood.txt");
r = 0;
c = 0;
while(food[r][c] != '\0')
{
oFood << food[r];
r++;
oFood << endl;
}
oFood.close();
return 0;
}
INPUT FILE: food.txt (this one is fine)
Candy
turkey
steak
potatoes
OUTPUT FILE: oFood.txt
Candy
turkey
steak
potatoes
potatoes <-----HERE I'm getting the duplicate, it's showing up as an extra in my char array, it's clobbering the bounds as well
Am I missing something? I don't see any bounds checking on r (starting on line 52.) When r == 4 (out of bounds), I bet it's printing the data in buffer. After r == 5, you're lucky it doesn't print junk.