Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First of all, your <code>while</code> loop is wrong. In fact, such <code>while</code> loop is <em>almost</em> always wrong.</p> <p>You should be writing the loop as:</p> <pre><code>while (myReadFile &gt;&gt; output) { if (line &gt; 20) { cout &lt;&lt; output; } line++; } </code></pre> <p>Your <code>while(!myReadFile.eof())</code> loop is wrong, because the <code>eof</code> flag (or any other failure flag) is set <em>after</em> an attempt to read from the stream fails; that means, if the attempt to read fails, you're still outputting, because you're still inside the loop, and the rest of the code in the loop still executes when it in fact should not.</p> <p>In my version, however, if an attempt to read (i.e <code>myReadFile &gt;&gt; output</code>) fails, then returned <code>std::istream&amp;</code> <em>implicitly</em> converts into <code>false</code>, and the loop exits immediately. And if it doesn't fail, the returned stream <em>implicitly</em> converts to <code>true</code>.</p> <p>By the way, it seems to me that you want to read line-by-line, instead of word-by-word. If so, then you should write this as:</p> <pre><code>std::string sline; //this should be std::string while (std::getline(myReadFile, sline)) { if (line &gt; 20) { cout &lt;&lt; sline; } line++; } </code></pre> <p>Again <a href="http://www.cplusplus.com/reference/string/getline/" rel="nofollow"><code>std::getline</code></a> returns <code>std::istream</code>. If the read was successful, the returned stream <em>implicitly</em> converts to <code>true</code> and the loop will continue, or if it was unsuccessful, then it would <em>implicitly</em> convert to <code>false</code> and the loop will exit.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload