consider this code snippet
void make(int n)
{
std::string user_input;
std::istringstream iss(user_input);
char letter;
int index;
while(n>0)
{ cout<<n<<endl;
std::getline(std::cin, user_input);
while (iss >> letter >> index)
cout<<letter<<' '<<index;
n--;
}
}
int main()
{ int n;
cin>>n;
make(n);
return 0;
}
here loop is not running correctly
if i put n=5 then output is
5
//getline doesn’t work
4
then getline works… why this
The reason why it’s doing this, is because when you’re calling
getline(), it’s taking what’s incinand putting it in the variable. However, when you initially calledcinto take in the inital input, the newline character remained in the buffer after going into yourmake()function.So when you enter the loop, the first
getline()takes'\n'fromcin, and the buffer was cleared. That’s why it seems to “skip” the first iteration as it would seem.So in order to get it to function correctly, you should clear your input buffer when you call your function using
cin.ignore(), like so:I haven’t used c++ much recently, so at the moment, i’m not sure if there’s a better way to handle this, but this should give you a good direction.