When you use ignore() in C++, is there a way to check those values that were ignored? I basically am reading some # of chars and want to know if I ignored normal characters in the text, or if I got the newline character first. Thanks.

网友答案:

I don't believe so - you'd have to "roll your own".

In other words, I think you'd have to write some code that read from the stream using get(), and then add some logic for keeping what you need and ignoring the rest (whilst checking to see what you're ignoring).

网友答案:

If you don't actually want to ignore the characters, don't use ignore() to extract them. get() can do the same job but also stores the extracted characters so that you can inspect them later.

网友答案:

If you provide the optional delim parameter to ignore(), then it can stop at a newline:

streampos old = is.tellg();
is.ignore(num, '\n');
if (is.tellg() != old + num) {
// didn't ignore "num" characters, if not eof or error then we
// must have reached a newline character.
}

There's a snag, though - when ignore() hits the delimiter, it ignores that too. So if you hit the delimiter exactly at the end of your set of ignored characters, then tellg() will return old + num. AFAIK there's no way to tell whether or not the last character ignored was the delimiter. There's also no way to specify a delimiter that isn't a single character.

I also don't know whether and when this is likely to be any faster than just reading num bytes and searching it for newlines. My initial thought was, "which part of the difference between ignore() and read() is non-obvious?" ;-)