what is the buffer problem in cin.getline and how can it be solved?
CPP - Character Arrays | Using cin.getline()
Hello @17manishms,
When you read anything from the standard input device, it firstly goes into the input buffer.
The input buffer is a location that holds all incoming information before it continues to the CPU for processing.
So, when compiler will take the value of k using cin statement. It will automatically insert a ‘\n’ at the end. After reading the value of k from the buffer, ‘\n’ will still remain in the buffer.
cin.getline() treats ‘\n’ as a delimiter.
Thus, it will read ‘\n’ present in the buffer and would terminate, storing an empty string in s.
By using cin.ignore(), you can ignore the ‘\n’ present in the buffer.
Example:
cin>>k;
cin.ignore(); //This is the solution to the problem.
getline(cin,s);
// cin.ignore() is a predefined function which ignores/clears one or more characters from the input buffer.
Hope, this would help.
Give a like if you are satisfied.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.