title: Reading from text file until EOF repeats last line
body: <p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  using namespace std;
  
  int main()
  {
      ifstream iFile("input.txt");    // input.txt has integers, one per line
  
      while (!iFile.eof())
      {
          int x;
          iFile &gt;&gt; x;
          cerr &lt;&lt; x &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p><strong>input.txt</strong>:</p>
  
  <pre><code>10  
  20  
  30
  </code></pre>
  
  <p><strong>Output</strong>:</p>
  
  <pre><code>10  
  20  
  30  
  30
  </code></pre>
  
  <p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>