Introduction
This article will discuss an amazing technique for the Fast I/O or Fast Input/Output in C++. This method reduces the input and output time of our C++ program and makes it more optimised. This method helps us to save time in programming contests.
This method is widely used by most C++ Competitive programmers around the world. This technique is known as Fast I/O or Fast Input/Output.
Fast I/O in C++
As we all know, C++ is a backward compatible language, which means it supports the majority of the syntax of the C programming language.
For output and input in C programming, we use the printf() and scanf() functions, respectively.
In C++, we can take input using scanf() and output using cin and printf() and cout.
Many people recommend using scanf() and printf() instead of cin and cout to achieve fast input and output, but we can do the same with cin and cout by using these two lines inside the main function:
ios_base::sync_with_stdio(false);
cin.tie(NULL);
By default, cin is synchronised with stdio, which causes it to avoid any input buffering, resulting in a lot of overhead for every character. We can enable input buffering by including the following code at the top of your program:
std::ios base::sync with stdio(false);
After adding this line, the stream will now read in chunks instead of reading one character at a time.
So now the question is, why isn't it always turned on?
Both cin and scanf have their own buffers. If this was set to 'on' by default and you took input with cin, the buffer would contain more than intended because it reads in chunks.
By using the Second line, we can untie the cin and cout streams:
cin.tie(NULL);
This connection between cin and cout means that when we use cin, cout must be flushed to provide the output, and when we provide the output, cin must be flushed to accept other input.
This synchronisation is useful in interactive problems where we need to use cin and cout repeatedly. Still, it is inefficient in competitive programming because it slows down the process for large I/O operations.