Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The two functions you are using don't have the effect you expect them to have:</p> <ol> <li><code>clear()</code> doesn't affect the buffer at all but rather clears the error flags. That is, if there was an unsuccessful read a flag is set (<code>std::ios_base::failbit</code>). While any error flag is set (there are a few more), the stream won't attempt to read anything.</li> <li><code>setbuf(0, 0)</code> affects the stream's internal buffer to not exist (calls with non-null values have implementation-defined meaning which is typically "do nothing"). This is generally a Bad Idea because it causes the streams to be very slow. Also, the keys pressed by a user are probably not stored in this buffer anyway but rather in the operating systems input buffer until they are sent to application (there are platform specific ways to turn off the operating system input buffer, e.g., on POSIX you'd use <code>tcsetattr()</code> to set the input into non-canonical mode).</li> </ol> <p>In either case, not having a buffer doesn't really help you anyway: The user may very well have typed valid input. The proper approach is to attempt reading the available input and, if this fails, to rid of the offending character (or characters). To this end you'd attempt to read the input and if it fails you'd <code>clear()</code> the stream and <code>ignore()</code> one or more characters (this example ignores an entire line; call <code>ignore()</code> without parameters to just ignore one character):</p> <pre><code>T value; while (!(std::cin &gt;&gt; value)) { std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } </code></pre> <p>You always need to verify that the input was successful anyway and the few extra lines are just adding a bit of recovery code.</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