Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>cin</code>'s base class is <a href="http://en.cppreference.com/w/cpp/io/basic_istream" rel="nofollow"><code>std::basic_istream</code></a>. The input stream indicates a recoverable error in case it cannot extract the requested data from the stream. In order to check for that error bit, <a href="http://en.cppreference.com/w/cpp/io/basic_ios/fail" rel="nofollow"><code>std::basic_istream::fail()</code></a> method must be used — it returns <code>true</code> if there was a failure or <code>false</code> if everything is alright. It is important to remember that if there is an error, the data is left in the stream and, of course, the error bit(s) must also be cleared using <a href="http://en.cppreference.com/w/cpp/io/basic_ios/clear" rel="nofollow"><code>std::basic_istream::clear()</code></a>. Also, a programmer must ignore incorrect data, or otherwise an attempt to read something else will fail again. For that purpose, <a href="http://en.cppreference.com/w/cpp/io/basic_istream/ignore" rel="nofollow"><code>std::basic_istream::ignore()</code></a> method can be used. As for the valid range of values, it must be checked manually. Okay, enough theory, here is a simple example:</p> <pre><code>#include &lt;limits&gt; #include &lt;iostream&gt; int main() { int n = 0; for (;;) { std::cout &lt;&lt; "Please enter a number from 1 to 10: " &lt;&lt; std::flush; std::cin &gt;&gt; n; if (std::cin.fail()) { std::cerr &lt;&lt; "Sorry, I cannot read that. Please try again." &lt;&lt; std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); continue; } if (n &lt; 1 || n &gt; 10) { std::cerr &lt;&lt; "Sorry, the number is out of range." &lt;&lt; std::endl; continue; } std::cout &lt;&lt; "You have entered " &lt;&lt; n &lt;&lt; ". Thank you!" &lt;&lt; std::endl; break; } } </code></pre> <p>Hope it helps. Good Luck!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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