0

I want to read the data from the file afile.dat and then print the data to the screen. The content of the file is as follows:

Max
20

In order to print the two items to the screen I wrote the following C++ program:

#include <fstream>
#include <iostream>
using namespace std;


int main () 
{

   char data[100];

   ifstream infile; 
   infile.open("afile.dat"); 

   cout << "Reading from the file" << endl; 

   while(infile){   
        infile >> data;
         cout << data << endl;  
   }

   infile.close();

   return 0;
}

The output of this program is:

Max
20
20

Why is "20" printed twice?

Tommy
  • 421
  • 3
  • 9
  • 21
  • `while(infile >> data)` Test for errors on the read, because the error won't be set until after you've performed a bad read and used the incorrect data. – Retired Ninja Jan 02 '17 at 23:50
  • to expand on @RetiredNinja, the final call to `infile >> data` fails to read a value for `data` but it's stell set from the last time. That failure then triggers the `while(infile)` to fail on the _next_ iteration. – Daniel Farrell Jan 02 '17 at 23:52
  • You should not loop on the state of the file, but on the return value of a read operation. See https://latedev.wordpress.com/2012/12/04/all-about-eof for why. –  Jan 02 '17 at 23:53
  • Exact same issue, only without explicitly writing `.eof()`. – Baum mit Augen Jan 02 '17 at 23:53
  • You could try `while(!infile.eof())` – ppham27 Jan 02 '17 at 23:54
  • 1
    @ppham27 No. Even reading the title of the dupe would have told that's not correct. – Baum mit Augen Jan 02 '17 at 23:58
  • @BaummitAugen It does actually work in this case as tested on my local machine, but in general, it's clear that you're right. – ppham27 Jan 03 '17 at 00:05

0 Answers0