Reading ifstream and getting duplicate

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?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
  using namespace 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.
Hmmm.

Ya know, you're right!

Thanks.
Topic archived. No new replies allowed.