I appreciate your attention to my question! Have 2 functions - fill() and Sum(). Then Sum() called after fill(), I got (!cin)
.
I found what when I replace while (cin>>u){}
with cin>>u
there is no problem, but I need multiply 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.
}
CodePudding user response:
When this loop has 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