title: How to use two cin statement in c++
body: <p>I am in doubt about how cin works with two statements, in my program I need to get at first, a sequence of numbers from the user and put them in a vector, and after a number B which will sum the first B elements of that vector, for example, if the user enters the sequence 5, 4, 3, 2, 1 and to B she enters 3, so the program will sum 5, 4 and 3. But the problem is that the second user input to A is handing the value to B, I used a while loop to get the sequence of values to A but from the second value the cin goes to B and then I get a out_of_range error, here is my code: </p>
  
  <pre><code>#include "std_lib_facilities.h"
  using namespace std;
  
  vector&lt;int&gt; nums;
  void sum();
  
  int main()
  {
      int a;
      cout &lt;&lt; "Please enter some numbers (press | at prompt to stop)" &lt;&lt; endl;
      while(cin&gt;&gt;a) nums.push_back(a); //get a series of numbers
  
      sum();
  }
  
  void sum()
  {
  
      int b,c = 0;
      cout &lt;&lt; "Please enter how many of the numbers you wish to sum, starting from the first" &lt;&lt; endl;
      cin&gt;&gt;b; //get the number of elements the user wants to sum
      for(int i = 0; i &lt; b+1; ++i){
          c += nums[i];
      }
  
      cout &lt;&lt; "The sum of the first " &lt;&lt; b &lt;&lt; " numbers is " &lt;&lt; c &lt;&lt; endl;
  }
  </code></pre>
  
  <p><strong>The correct code</strong></p>
  
  <pre><code>#include "std_lib_facilities.h"
  #include &lt;limits&gt;
  using namespace std;
  
  vector&lt;int&gt; nums;
  void sum();
  
  int main()
  {
      int a;
      cout &lt;&lt; "Please enter some numbers (press | at prompt to stop)" &lt;&lt; endl;
      while(cin&gt;&gt;a){
          nums.push_back(a);
  }
      cin.clear();         // HERE IS WHAT
      cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\n'); // WAS MISSING 
      sum();
  }
  
  void sum()
  {
  
  int b,c = 0;
  cout &lt;&lt; "Please enter how many of the numbers you wish to sum, starting from the first" &lt;&lt; endl;
  cin&gt;&gt;b;
  for(int i = 0; i &lt; b; ++i){
  c += nums[i];
  }
          cout &lt;&lt; "The sum of ";
      for(int d = 0; d &lt; b; ++d){
              if(d == b-1) cout &lt;&lt; " and " &lt;&lt; nums[d];
              else cout &lt;&lt; nums[d] &lt;&lt; " ";
      }
          cout &lt;&lt; " is " &lt;&lt; c &lt;&lt; endl;
  }
  </code></pre>