The reference page for ignore() describes the parameters, but perhaps in too technical a way to begin with.
Quote:
cplusplus_com wrote: |
---|
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. |
The starting point is that the input stream is buffered. When prompted to enter a number, the user might enter something like "123" and then press enter. All of that, including the newline generated when the enter key is pressed, gets stored in the buffer, "123\n".
After processing the
cin >> nNum
, the numeric characters which can be interpreted as an integer are extracted from the buffer, but the newline '\n' isn't part of the number, so it remains behind in the buffer.
cin.ignore()
with no parameters will just read and discard a single character from the buffer, which might be sufficient.
But what if, when prompted for a number, the user typed
" 123 hello \n"? Any leading spaces will be read and discarded, but any trailing characters whether spaces or anything else, will get left behind.
So we can tell the ignore() function to ignore more than one character. But how many? Well, we don't know what was typed by the user, so I just chose a large number, 1000.
cin.ignore(1000)
tells the function to read and ignore the next 1000 characters. But hold on, the user may not have typed that many, and the command will sit there waiting for the next 999 characters, that's no good. So we add a delimiter, which tells ignore to stop processing after it has read that particular character. Hence the form I chose,
cin.ignore(1000, '\n');
which means ignore up to 1000 characters, or until a newline is found. The number 1000 is entirely arbitrary, I just chose that because it is usually sufficient.