Why is it skipping the first getline?

It outputs everything here, except it skips the first call to getline. It calls the second getline.

Why is it skipping the first getline?

1
2
3
4
5
6
7
8
9
10
   string newQuestion, animal;
                         cout << "What yes or no question would have helped?" << endl;
                         getline(cin, newQuestion);
                         cout<<"Question asked: " << newQuestion << endl;
                         cout << "What was your animal?" << endl;//!!
                         getline(cin, animal);
                         cout<<"Animal added: " << animal << endl;//!!
                         addRight(nd, nd->data);
                         addLeft(nd, animal);
                         nd->data = newQuestion;
The cause is probably elsewhere in the program.
if you have code like this:
1
2
int x;
cin >> x;

... after the cin, there will be a newline character remaining in the input buffer. That will be accepted by the next getline, meaning the user doesn't get the opportunity to type anything.

The solution is to clear the input buffer by something like
cin.ignore(); before the start of the code where you are using getline.

And it worked. Thank you. I've never heard of cin.ignore(); before, so now I'm inclined to look at all the member functions of the iostream classes. Thank you.
Topic archived. No new replies allowed.