1

The various unformatted input functions on std::istream (well, really, std::basic_istream) like read(), readsome(), getline(), and ignore() all return a stream. When processing the results it is often important to know how many character were actually read. Relying on a null character in the string obviously doesn't work for binary files or ignore() which doesn't even involve any string, i.e., something like strlen() is entirely out of question.

How can the number of characters which were read by the last unformatted input operation using an std::istream, or more generally, std::basic_istream, be determined?

Dietmar Kühl
  • 141,209
  • 12
  • 196
  • 356
  • You've mentioned `std::istream::gcount` in your recent answer, what are your concerns? – LogicStuff Dec 20 '15 at 22:31
  • 2
    @LogicStuff: my recent answer was on `readsome()` which does include the answer but the question is unlikely to be found by anybody using `std::istream::getline()` or `std::istream::read()` while this question has more hope of being found when someone looks determining the number of characters being read. – Dietmar Kühl Dec 20 '15 at 22:34
  • 1
    @LogicStuff: I expect this to be an FAQ-style question. I don't think Dietmar would need SO to actually answer any questions about C++ :-) – Kerrek SB Dec 20 '15 at 22:34

1 Answers1

4

Use the gcount() member function of the basic_istream base class to retrieve the count of characters obtained by the last unformatted input operation.

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025