Fast I/O optimization for cin/cout in C++

Some problems have a huge amount of input and output data. Here are some tips for optimizing I/O through cin/cout. Without these optimizations cin and cout maybe too slow.
All code snippets provided assume that you have included the required headers and are using namespace std;

set sync with stdio to false

C++ allows both C and C++ styled I/O in order to remain backward compatible. So each I/O operation performed on standard C++ streams (such as cin/cout/cerr) are also performed on the standard C streams. We can save a lot of time by not requiring this synchronization. We can do that by:
When you set synchronization to false you cannot intermix C++ styled I/O and C styled I/O (scanf/printf etc.)

untie cin and cout

Usually when you output someting to cout it is not output immediately to stdandard output but stored in a buffer. It has to be flushed for the content to be actually output. Flushing usually happens when the buffer is full or the program is being terminated. To facilitate interaction with the user via cin/cout whenever cin is used cout is flushed. This is to help with user prompt. Consider the following snippet:
Since cin and cout are tied, the cout's buffer is flushed before cin executes allowing the user to see the prompt. However in coding contests we don't need this. So we can untie cout from cin by doing this:

Avoid using endl

We usually use endl for ending a line of output in cout. But it also has the side effect of flushing cout. So avoid using endl and use '\n' instead to take full advantage of bufferring. This is especially useful if you have to output a large number of lines.


Before using these optimizations do try to understand the what and why of each optimization. Otherwise they may cause strange, hard-to-debug bugs. Note that with above optimization you will have to manually flush cout for interactive problems. You can do that using:

Where to put those statements

Those statements should be at start of the program. You can put them in main as the first few lines or if you don't like cluterring main you can use this trick:

More optimizations

There are ofcourse more I/O optimizations that can be performed. But these should be enough for the vast majority of problems. See the references for links to articles on more advanced optimizations.
C++ I/O benchmark
Fast I/O using getchar
Discussion on advanced fast I/O
Fast I/O using getc