Is there any way to peek at the stdin buffer?

Portably, you can get the next character in the input stream with getchar() and then push it back with ungetc(), which results in a state as if the character wasn’t removed from the stream. The ungetc function pushes the character specified by c (converted to an unsigned char) back onto the input stream pointed to … Read more

std::fstream buffering vs manual buffering (why 10x gain with manual buffering)?

This is basically due to function call overhead and indirection. The ofstream::write() method is inherited from ostream. That function is not inlined in libstdc++, which is the first source of overhead. Then ostream::write() has to call rdbuf()->sputn() to do the actual writing, which is a virtual function call. On top of that, libstdc++ redirects sputn() … Read more

When does cout flush?

There is no strict rule by the standard – only that endl WILL flush, but the implementation may flush at any time it “likes”. And of course, the sum of all digits in under 400K is 6 * 400K = 2.4MB, and that’s very unlikely to fit in the buffer, and the loop is fast … Read more

How to disable buffering on a stream?

For file streams, you can use pubsetbuf for that : std::ifstream f; f.rdbuf()->pubsetbuf(0, 0); f.open(“test”); Explanation The C++ standard says the following about the effect of setbuf (and thus pubsetbuf) for file streams : If setbuf(0,0) is called on a stream before any I/O has occurred on that stream, the stream becomes unbuffered. Otherwise the … Read more