In C++, ignore() reads characters from an input stream and throws them away. You choose when it stops: after a number of characters, or when it has removed a chosen delimiter such as the new line.
It is the standard way to clean up the input buffer, for example to remove the leftover Enter key after cin >> number. Include <iostream> to use it.
This is a member function of std::istream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call ignore on an input stream. Both arguments are optional.
C++
in.ignore(); // skip one character
in.ignore(5); // skip five characters
in.ignore(1000, '\n'); // skip up to and including '\n'
#include <limits>
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Call
What it does
in.ignore()
Skips exactly one character.
in.ignore(n)
Skips up to n characters.
in.ignore(n, '\n')
Skips characters until it has removed a new line, or after n characters, whichever comes first.
For a limit that can never be too small, use std::numeric_limits<std::streamsize>::max() from <limits>.
ignore(100, '\n') skips characters until it has removed the first new line. The limit 100 is just a safe maximum.
The whole first line is gone, new line included.
getline() reads from the start of the second line, so only second line is printed.
Example 3 — Skip a Comment Behind a Number
Read a number, ignore the comment on the same line, then read the next number.
C++
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("10 # first value\n20 # second value\n");
int a = 0;
int b = 0;
in >> a;
in.ignore(100, '\n');
in >> b;
std::cout << "a = " << a << '\n';
std::cout << "b = " << b << '\n';
return 0;
}
Output
a = 10
b = 20
How It Works
in >> a reads 10 and stops at the space. The comment text is still waiting.
ignore(100, '\n') removes the comment and the new line at its end.
The next in >> b starts at 20. Without ignore() it would meet the # sign and fail.
Frequently Asked Questions
It reads characters from cin and discards them. With no arguments it skips one character. With a count and a delimiter it skips until the delimiter has been removed or the count is reached.
cin >> x leaves the Enter key (a new line) in the buffer. Skipping it lets a following getline() read the real next line.
It is the largest possible count, so ignore() will skip everything up to the delimiter, however long the line is. It needs #include <limits>.
Yes. The delimiter is read and discarded together with the characters before it.
A failed stream refuses all reading. Call cin.clear() first to reset the flags, then call cin.ignore().