Faster I/O


You may have come across programming challenges where you are asked to use “faster I/O”. For those of you who have been in the sport programming arena for a while, you already know why you need to do this. This instruction in a challenge is the telltale sign that the test cases contains large input/output data.

How Do You Use Faster I/O?

The answer to this depends on which programming language you are using.

C++

If you are using C++, you can easily switch to faster I/O by adding the following two lines at the beginning of your main() function:

ios_base::sync_with_stdio(false);
cin.tie(NULL);

You must call ios_base::sync_with_stdio(false) before performing any input/output operation. And so, it is a good idea to do it at the beginning of your main function. The effect doing it later is implementation-specific and may not work as expected.

When this function is called with false, it disables synchronization of C++ streams with C streams after each input/output operation.

In addition to this, you can use '\n' at the end of a cout instead of endl:

cout << x << '\n';

Alternatively, you can use printf and scanf in C++ by including “stdio.h”.

printf("%d\n", x);

Further Reading


Discussion