Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I sense that you had some formatted input earlier in your program, i.e., it looks something like this:</p> <pre><code>std::cin &gt;&gt; value; do_something(value); std::cout &lt;&lt; "press enter to end\n"; std::cin.ignore(); </code></pre> <p>If that is the case, you have some character in the input buffer from the time you entered <code>value</code>. For example, there can be a <code>'\n'</code> but it can be any odd other characters, too. This character will be read when the program encounters <code>std::cin.ignore()</code>.</p> <p>What you <em>probably</em> want to is to get rid of the characters currently known to be in the buffer. This isn't quite what would be done as this can still miss characters which are already entered but not, yet, transferred but there is no portable approach to clear all potential characters (it is normally not a problem because hardly any user interface depends on character input from a terminal).</p> <p>To ignore the characters which are known to be present you need to start off by breaking the connection between <code>&lt;stdio.h&gt;</code> and IOStreams using <code>std::ios_base::sync_with_stdio()</code> and later consume the known characters entered after your last read, e.g.,</p> <pre><code>#include &lt;iostream&gt; int main() { std::ios_base::sync_with_stdio(false); int x; std::cin &gt;&gt; x; std::cin.ignore(std::cin.rdbuf()-&gt;in_avail()); std::cout &lt;&lt; "press enter\n"; std::cin.ignore(); } </code></pre> <p>The odd call to <code>sync_with_stdio()</code> is necessary to have the IOStreams actually buffer the characters received from the system rather than reading characters individually. As a nice side effect it <strong>dramatically</strong> improves the performance of using <code>std:cin</code>, <code>std::cout</code>, and the other standard stream objects.</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