0

Why does cin.getline() jumps to the next code line? How to solve it?

I am writing a code in c++ that collects employees info as id, name and salary amount. So i have a loop where i collect this info for many employees, but when i want to enter the name and last name of the first employee using cin.getline the code just jumps into the next code line. So i cant then enter the names and lastnames. Im using cin.getline because of the space that exist between the name and lastname when i enter these info. What can i do to solve this?

28th Nov 2018, 5:04 AM
Juan José Fernández
1 ответ
0
I bet you're doing something like this cin>>var; cin.getline(str, len); Getline take a string with new line character as terminator, In this case cin >> actually leave new line character in the buffer. So what happen ? Getline read the newline character in the buffer and think that is your input, because there's only newline character in there it'll think that you already finish the input and take whatever left in the buffer which is sometimes nothing. How to solve it ? Use cin.ignore() before getline, it'll take care of character left in the buffer But cin.ignore only clear 1 character from the buffer, if you're not sure you can keep callinh cin.ignore() until it reach '\n'
28th Nov 2018, 6:27 AM
Taste
Taste - avatar