My program is reading the last line of data from an infile twice. When I execute the program, the last line of data is being displayed twice. Please Help!

Hey Erica,
Welcome to the forum. I not a big expert or anything but I do know that most of the people like to see the program code so they can tell you exactly what is wrong. Hopefully someone can help.

>My program is reading the last line of data from an infile twice.
I'll bet my next paycheck that your file processing loop looks like this:

while ( !feof ( in ) ) {
  /* Read from the file and process */
}

Or this:

while ( !in.eof() ) {
  // Read from the file and process
}

The problem with that is feof (or stream.eof ) only returns true after an attempt has been made to read from the file and end-of-file was encountered. So your loop will iterate once more than you want, and because the input request failed you will use the last successfully read line. The result is that the last line of the file is processed twice.

The solution is to use the return value of your input function as the loop condition:

while ( fgets ( line, sizeof line, in ) != NULL ) {
  /* Process and print */
}

Or

while ( getline ( in, line ) ) {
  // Process and print
}

As an alternative, you can use an infinite loop and use feof or stream.eof in an if statement immediately after your input functions read from the file. That way you can break from the loop before processing the last line twice.

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.