You have a few options.
You could just call cin.getline()
, which will retrieve the remainder of the line including the newlines and leave the pointer at the start of the next line. Works as long as you know the remainder of the input line is ignorable.
You can also use cin.ignore(1)
or cin.ignore(2)
if you know a newline is next. For input streams that produce CR+LF instead of just one, you'll have to ignore two characters, and it's up to you to figure out if you're getting CR or CR+LF.
Another option is to use cin.peek()
to check what the next character is ahead of time. That way you can use skip newlines without consuming non-newline characters. For example:
void skipNewlines (istream &in) {
int ch;
while ((ch = in.peek()) == '\r' || ch == '\n')
in.ignore();
// and now newlines skipped and next in.get() will read the next char.
}
You could modify that to skip all whitespace. That option probably works the smoothest with your use of cin >> T
.
You could also consider writing your own character input function that reads the next character but ignores line breaks (or whatever). For example:
int getWithoutNewline (istream &in) {
int ch;
do {
ch = in.get();
} while (ch == '\n' || ch == '\r');
return ch;
}
Then use getWithoutNewline(cin)
instead of cin.get()
to read characters when parsing your integers. You have flexibility there; you could e.g. translate the newlines to spaces. This has the advantage of being able to operate without you having to know anything about the location or form of the line breaks. However, it may not work for all situations.
Personally, I wouldn't take the approach of just blindly discarding all contents. I'm not even sure if that's reliably possible given that there's no end-of-file after each line. The closest approximation to what you're asking for, as far as this goes, is to just call getline()
to read and consume the rest of the line (including the newlines).
Pick whichever one of those, or some variant of one of those, suits your application and usage the best.