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()
?
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()
?
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 (likestd::getline()
) but following a formatted extraction (likestd::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.
You only need to use
cin.ignore()
when there's some previous input you haven't read. If there isn't, then you don't need to and it will cause you to ignore something you want. The most common case is to ignore a newline character the ended a previous line.If someone types "foo<enter>bar" and you want to read "foo" then "bar", you need to ignore the <enter> between them (or use a function that does so automatically).