<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>

[{'answer_id': 21656, 'author': 'wilhelmtell', 'author_id': 456, 'author_profile': 'https://Stackoverflow.com/users/456', 'pm_score': 8, 'selected': True, 'text': '<p>Just follow closely the chain of events.</p>\n\n<ul>\n<li>Grab 10</li>\n<li>Grab 20</li>\n<li>Grab 30</li>\n<li>Grab EOF</li>\n</ul>\n\n<p>Look at the second-to-last iteration.  You grabbed 30, then carried on to check for EOF.  You haven\'t reached EOF because the EOF mark hasn\'t been read yet ("binarically" speaking, its conceptual location is just after the 30 line).  Therefore you carry on to the next iteration.  x is still 30 from previous iteration.  Now you read from the stream and you get EOF.  x remains 30 and the ios::eofbit is raised.  You output to stderr x (which is 30, just like in the previous iteration).  Next you check for EOF in the loop condition, and this time you\'re out of the loop.</p>\n\n<p>Try this:</p>\n\n<pre><code>while (true) {\n    int x;\n    iFile &gt;&gt; x;\n    if( iFile.eof() ) break;\n    cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>By the way, there is another bug in your code.  Did you ever try to run it on an empty file?  The behaviour you get is for the exact same reason.</p>\n'}, {'answer_id': 21666, 'author': 'Patrick Loz', 'author_id': 2091, 'author_profile': 'https://Stackoverflow.com/users/2091', 'pm_score': 5, 'selected': False, 'text': '<p>I like this example, which for now, leaves out the check which you could add inside the while block:</p>\n\n<pre><code>ifstream iFile("input.txt");        // input.txt has integers, one per line\nint x;\n\nwhile (iFile &gt;&gt; x) \n{\n    cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Not sure how safe it is...</p>\n'}, {'answer_id': 21787, 'author': 'wilhelmtell', 'author_id': 456, 'author_profile': 'https://Stackoverflow.com/users/456', 'pm_score': 4, 'selected': False, 'text': '<p>There\'s an alternative approach to this:</p>\n\n<pre><code>#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n\n// ...\n\n    copy(istream_iterator&lt;int&gt;(iFile), istream_iterator&lt;int&gt;(),\n         ostream_iterator&lt;int&gt;(cerr, "\\n"));\n</code></pre>\n'}, {'answer_id': 14836904, 'author': 'Solostaran14', 'author_id': 1033530, 'author_profile': 'https://Stackoverflow.com/users/1033530', 'pm_score': 3, 'selected': False, 'text': '<p>Without to much modifications of the original code, it could become :</p>\n\n<pre><code>while (!iFile.eof())\n{  \n    int x;\n    iFile &gt;&gt; x;\n    if (!iFile.eof()) break;\n    cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>but I prefer the two other solutions above in general.</p>\n'}, {'answer_id': 15958291, 'author': 'user1384482', 'author_id': 1384482, 'author_profile': 'https://Stackoverflow.com/users/1384482', 'pm_score': 2, 'selected': False, 'text': '<pre><code>int x;\nifile &gt;&gt; x\n\nwhile (!iFile.eof())\n{  \n    cerr &lt;&lt; x &lt;&lt; endl;        \n    iFile &gt;&gt; x;      \n}\n</code></pre>\n'}, {'answer_id': 27273529, 'author': 'Brian Jack', 'author_id': 669580, 'author_profile': 'https://Stackoverflow.com/users/669580', 'pm_score': 3, 'selected': False, 'text': "<p>The EOF pattern needs a prime read to 'bootstrap' the EOF checking process.  Consider the empty file will not initially have its EOF set until the first read.  The prime read will catch the EOF in this instance and properly skip the loop completely.</p>\n\n<p>What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file.  Reading the exact amount of data will not flag the EOF.</p>\n\n<p>I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.</p>\n\n<ul>\n<li>0</li>\n</ul>\n\n<p>So add a prime read and move the loop's read to the end:</p>\n\n<pre><code>int x;\n\niFile &gt;&gt; x; // prime read here\nwhile (!iFile.eof()) {\n    cerr &lt;&lt; x &lt;&lt; endl;\n    iFile &gt;&gt; x;\n}\n</code></pre>\n"}, {'answer_id': 27585094, 'author': 'Raf', 'author_id': 930502, 'author_profile': 'https://Stackoverflow.com/users/930502', 'pm_score': 2, 'selected': False, 'text': '<p>At the end of the last line, you have a new line character, which is not read by >> operator and it is not an end of file.\nPlease, make an experiment and delete the new line (thelast character in file) - you will not get the duplication.\nTo have a flexible code and avoid unwanted effects just apply any solution given by other users.</p>\n'}]
['https://Stackoverflow.com/questions/21647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1630/']