Search code examples
c++cin

cin is being ignored when another cin was previously used


Have 2 functions - fill() and Sum(). When Sum() is called after fill(), I get (!cin).

I found that when I replace while (cin>>u){} with cin>>u, there is no problem, but I need to multiply the input.

void fill (vector <int>& x){
    int u;
    while (cin>>u){
        x.push_back(u);   
    }
#include <stdexcept>
#include <iostream>
#include <vector>

int Sum (std::vector<int>& x){
  std::cout << "Enter number: ";
  int number;
  std::cin >> number; //THIS LINE 
  if (!std::cin){
    throw std::runtime_error (" "); // semicolon was missing before edit
  }
  if(number >= 0 && number < x.size()){
    //doing smthg
  }
  return 0; // was missing before edit.
}

Solution

  • When this loop finishes

    while (cin>>u){
        x.push_back(u);   
    }
    

    it is because cin>>u has returned false. When this happens (however it happens, unfortunately you didn't say) cin will be in an error state and no further input will happen until you clear that error state. This explains what you have observed. Additionally you might need to clear any pending input, but can't say for certain until I understand precisely what input you are giving to your program

    Suggest you change the above code to this

    while (cin>>u){
        x.push_back(u);   
    }
    cin.clear(); // clear error state
    cin.ignore(999, '\n'); // clear pending input