In C++, gcount() tells you how many characters the last unformatted input function extracted from the stream. Unformatted functions are get(), getline(), read(), readsome(), and ignore().
It is most useful with read(), because a short read at the end of a file leaves you unsure how many bytes really arrived. 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 gcount right after an unformatted input call, before doing another read.
C++
in.read(buf, 10);
std::streamsize n = in.gcount(); // how many arrived
Call
What it does
in.gcount()
Returns the count of the last unformatted read.
in.read(buf, 10); in.gcount()
Tells you how many bytes arrived, which can be less than 10.
in.getline(buf, 50); in.gcount()
Includes the new line, even though it is not stored in buf.
Formatted reads such as in >> x do not change the count. gcount() keeps the value from the last unformatted call.
Library declarations
C++
streamsize gcount() const;
Parameters
Parameter
Description
None
gcount() takes no parameters.
Return Value
Return Value
Description
std::streamsize
The number of characters extracted by the last unformatted input call. It is 0 if no such call has been made.
C++ Examples
Example 1 — gcount() After getline()
The count includes the new line that getline() removed.