Hi,
i'm learning file creating and reading and i ran into a problem when i create a file with input using a loop i end up with an extra line at the end of the file and when reading the file i always get the last line repeated twice the only thing that helped was going to the file deleting that extra line but i was wondering is there a way around this?

here is the two loops i'm using to create and read the file, i also tried to use while(inFile.good()) instead of the eof() as some suggested from my google search but that didn't help

// loop for writing data
for (int i = 1; i < 11; ++i)
    {
        cout << "Enter a number: ";
        cin >> number;
        outFile << number << endl;
    }

// loop for reading the data

while (!inFile.eof())
    {
            inFile >> number;
            total += number;
            count++;
            cout << number << endl;
    }

thanks in advance!

Recommended Answers

All 4 Replies

while (!inFile.eof()) is never the way you want to read from the file. When reading the last line of the file the EOF flag does not get sent until it tries to read past the last line so while (!inFile.eof()) will actually read all lines in the file plus one. You should use a read operation to control the loop since once the read fails it stops the loop. Since you use inFile >> number; in your while loop you can rewrite it as the following:

while (inFile >> number)
{
    total += number;
    count++;
    cout << number << endl;
}

Nathan thanks for your reply, i tried the (infile >> number) but when i do that it only print every other line starting at second line.

Show we what code you used for that. Did you remove the line inFile >> number; from inside the while lop as that will cause a double read.

well that explains it Nathan lol, thanks it works now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.