C++: getline is beings skipped for user input

122 Views Asked by At

The first call for getline() is being skipped but the second call is working. What am I doing wrong?

string animal, q;
cout << "Darn, I lost. What was is?";

getline(cin, animal);//this is being skipped
cout << "Enter a question that is true for a(n) " << animal << " and false for a(n) " << question->value << ": ";
getline(cin, q);
3

There are 3 best solutions below

0
Sourav Kanta On

Looks like you had some other input before this.Put a getchar() before getline to consume buffer stored characters.

 getchar();
 getline(cin, animal);
1
mr nooby noob On

I figured it out, it was being somewhere else in my code I used the standard "cin" rather than getline(), and I guess there was still something in the buffer, like @Sourav Kanta said. I guess I should either use one or the other next time, and not both.

0
Saeid On

If data is like hello\n how are you? and you use cin to read hello and getline to read how are you? it won't work. because the getline will read \n and not the the following line to fix this. you can use cin.ignore() to ignore \n and then use getline to read the following line.