Trouble with c++ getline/loops | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Trouble with c++ getline/loops

task i created: get amount of people going to party for every person going give prompt for their name output their name and say they have been invited. use for loop problem: it doesn’t prompt the user for the first person, yet outputs that blank has been invited i think its a problem with the getline function https://code.sololearn.com/co1ociCiP7nm/?ref=app

27th Dec 2019, 1:25 PM
Bettalion
Bettalion - avatar
3 Answers
+ 4
That's because the newline character '\n' is still in the input buffer when getline() starts reading from it, so the first string it reads is empty. You have to empty the input buffer before starting to read in with getline(). One possible way is to include the <limits> header from the Standard Library, and then to put the following line before the for loop: cin.ignore( numeric_limits< streamsize >::max(), '\n' ); For other solutions, you can consult the following article: https://www.geeksforgeeks.org/clearing-the-input-buffer-in-cc/
27th Dec 2019, 2:11 PM
Shadow
Shadow - avatar
+ 2
Yes Shadow is right, this has happened to me a lot of times but I use to try different techniques to tackle it (sometimes even changed the whole logic of code) But using cin.ignore is a nice way Thanks Srinath Bn for asking this question so that I got to know about this new function
27th Dec 2019, 2:20 PM
Arsenic
Arsenic - avatar
+ 2
I can't help but to notice this loop. Why you use `x < party + 1` as the loop condition? This way when I enter 5, your code asks for 6 person names, does it not feel odd to you? cause it does to me. for (int x = 0; x < party + 1; x++)
27th Dec 2019, 2:32 PM
Ipang