In C++, readsome(buffer, count) reads up to count characters that are already available in the stream buffer. It does not wait for more data to arrive.
It returns how many characters it actually copied. With a string stream, every character is available, so it works like a gentle read() that never fails at the end. 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 readsome on an input stream. The returned number tells you how many characters you got.
C++
char buf[10];
std::streamsize n = in.readsome(buf, 10);
Call
What it does
in.readsome(buf, 4)
Copies up to four available characters and returns the number copied.
while ((n = in.readsome(buf, 4)) > 0)
Keeps reading until nothing is available.
in.readsome(buf, 10) == 0
True when there is nothing available at the moment.
How much is "available" depends on the stream. For std::cin on many systems it can be 0 even when you typed something. Use read() or getline() for normal input.
Both streams hold only abc, and both calls ask for ten characters.
readsome() copies the three available characters and stops quietly. No flag is set, so fail() is no.
read() also copies three, but it wanted ten. It sets eofbit and failbit, so fail() is yes.
Frequently Asked Questions
It reads up to count characters that are already in the stream buffer and returns how many it copied. It does not wait for more input.
read() insists on exactly count characters and fails if there are fewer. readsome() takes only what is available and does not fail for being short.
On many systems cin does not report buffered characters, so nothing counts as available. The result depends on the library, so use getline() for normal keyboard input.
No. Use the returned count to place a \0 yourself if you need a C string.
It does not wait, but it is not a full non-blocking solution. It depends on what the stream buffer already holds.