-3

I am a beginner to c++, and I just can't wrap my head around whats cin.ignore & cin.clear, they make absolutely no sense to me. When you explain this to me, please be very descriptive

2 Answers2

1

In C++ input processing, cin.fail() would return true if the last cin command failed.

Usually, cin.fail() would return true in the following cases:

  1. anytime you reach the EOF and try to read anything, cin.fail() would return true.
  2. if you try to read an integer and it receives something that cannot be converted to an integer.

When cin.fail() return true and error occurs, the input buffer of cin is placed in an "error state". The state would block the further input processing.

Therefore, you have to use cin.clear(). It would overwrite the current value of the stream internal error flag => All bits are replaced by those in state, if state is good bit all error flags are cleared.


For cin.ignore, first it would accesses the input sequence by first constructing a sentry object. After that, it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

Therefore, It commonly used to perform extracting and discarding characters. A classical cases of cin.ignore is that when you're using getline() after cin, it would leaves a newline in your buffer until you switch function. That why you MUST flush the newline out of the buffer.

Shiu Chun Ming
  • 227
  • 2
  • 13
0

std::cin.ignore() can be called three different ways:

No arguments: A single character is taken from the input buffer and discarded:

std::cin.ignore(); //discard 1 character

One argument: The number of characters specified are taken from the input buffer and discarded:

std::cin.ignore(33); //discard 33 characters

Two arguments: discard the number of characters specified, or discard characters up to and including the specified delimiter (whichever comes first):

std::cin.ignore(26, '\n'); //ignore 26 characters or to a newline, whichever comes first

source: http://www.augustcouncil.com/~tgibson/tutorial/iotips.html

Romeo
  • 1,135
  • 13
  • 26
  • The recommended ignore is `std::cin.ignore(std::numeric_limits::max(), '\n');`, but when using this in the general sense you have to be a bit careful. It's potentially waiting for a few kaijuzillion characters if it doesn't find a line feed and this is pretty much a waste of everybody's time. – user4581301 Jul 25 '17 at 01:52
  • ty for the tip and for this word "kaijuzillion" i love it. – Romeo Jul 25 '17 at 01:57
  • `std::numeric_limits::max()` is more than just a large number. It's a special case for `ignore()` that disables counting so it consumes all characters up to and including the delimiter. – Blastfurnace Jul 25 '17 at 02:02