Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several problems with your code. The most fundamental is that you do two inputs each time through the loop, the first in the <code>while</code>, and the second using <code>&gt;&gt;</code> in the loop. Note too that the second will skip any spaces, then convert the input to an integer. If the input cannot be legally converted to an integer (e.g. the next character is an <code>'a'</code>), the input goes into an error state, and <code>cin.get()</code> will always return <code>EOF</code>. And of course, if you are entering numbers, you can easily enter more than <code>25</code>, and overrun the buffer. </p> <p>If you just want to enter a sequence of numbers, then:</p> <pre><code>std::vector&lt;int&gt; fabcd; int tmp; while ( std::cin &gt;&gt; tmp ) { fabcd.push_back( tmp ); } </code></pre> <p>is all you need. (The numbers must be separated by white space.) If you want to enter the <em>digits</em>, up until you encounter a white space, something like the following should work:</p> <pre><code>std::vector&lt;int&gt; digits; int tmp = std::cin.get(); while ( tmp != EOF &amp;&amp; ! std::isspace( tmp ) ) { digits.push_back( tmp /* or tmp - '0' */ ); tmp = std::cin.get(); } </code></pre> <p>Notice that the results of <code>std::cin.get()</code> are assigned to an <code>int</code>, <em>not</em> a <code>char</code>. This function returns an <code>int</code> intentionally, because it must be able to return the out of band value <code>EOF</code>. There are a couple of variants on this: if you use <code>std::cin::peek()</code>, instead of <code>std::cin::get()</code>, you'll not actually extract the character (which you'll have to do in the loop); and there is also <code>std::get( char&amp; )</code>, which extract the character into the given <code>char</code>, provided it isn't at EOF. Using this function, the loop would be:</p> <pre><code>std::vector&lt;int&gt; digits; char tmp; while ( std::get( tmp ) &amp;&amp; ! std::isspace( tmp ) ) { digits.push_back( tmp ); } </code></pre> <p>(You might also want to use <code>std::isdigit</code>, instead of <code>! std::ispace</code> to control the loop.)</p> <h2>EDIT:</h2> <p>One last point: the actual numeric code for a space or whatever depends on the implementation, and is <em>not</em> necessarily 32. Also, you'll want to handle tabs and newlines similarly. You should always use the <code>isspace</code>, etc. functions. Or if you really do want to check for a space, and only a space, compare with <code>' '</code>, and not 32.</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