4

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()?

0x499602D2
  • 87,005
  • 36
  • 149
  • 233
Umer
  • 51
  • 1
  • 1
  • 8

2 Answers2

4

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).

David Schwartz
  • 166,415
  • 16
  • 184
  • 259
1

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.

Community
  • 1
  • 1
0x499602D2
  • 87,005
  • 36
  • 149
  • 233