Why do we need to use cin.ignore() before getline(cin, string)?

c++

Solution

`std::getline()` only "skips" input if there is a leading newline in the stream which precedes the input you wish to read. This can come about if you previously performed a formatted extraction which left a residual newline. By default, `std::getline()` delimits extraction upon the acquisition of a newline character.

`ignore()` is a function which discards a certain amount of characters (by default the amount to discard is 1). If you use this preceding an unformatted extraction (like `std::getline()`) but following a formatted extraction (like `std::istream::operator>>()`) it will allow the data to be read as you expect because it will discard the residual newline.

I talk about this in detail in my answer here.

Problem

Why do we need to use `cin.ignore()` before taking input in a string? What is the backhand process? Why does it skip the input in a string (if we call `getline` function for more variables) if we don't use `cin.ignore()`?

Original source

Related problems