I/O operations (1)
Course: C++ Part 1 - chapter 3
Output
Section titled “Output”For output, we can generally use cout statement.
cout<<"Hello World!";To print new lines, we can use endl or \n.
So let’s see what the difference is.
'\n' : It inserts a new line to the output stream.
endl : It inserts a new line and flushes the output stream.
So eventually
cout<<endl;
is equivalent to using
cout<<'\n'<<flush;
But which one to use? \n is much faster than endl. So use \n every time if possible (unless you need to flush the output). However, when you are printing a single element or some fixed set of elements (like 100), you can use endl as well.
💡 Note: By default, all streams (input and output) are tied together. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream. To untie, we can use
cout.tie(NULL);
For reading input, we generally use cin statement.
int x;cin>>x;
// We can even read multiple space or newline separated inputs like thisint x, y;cin>>x>>y;Fast IO
Section titled “Fast IO”Generally, as mentioned above, the input and output streams are tied, which causes flushing before every IO operation. This can make program execution slower in case of large input size. So we can untie the streams using the statements cin.tie(NULL) and cout.tie(NULL). Just add this at beginning of your program.
**std::ios_base::sync_with_stdio**
Sets whether the standard C++ streams are synchronized to the standard C streams after each input/output operation. In practice, this means that the synchronized C++ streams are unbuffered, and each I/O operation on a C++ stream is immediately applied to the corresponding C stream’s buffer. This makes it possible to freely mix C++ and C I/O.
In addition, synchronized C++ streams are guaranteed to be thread-safe (individual characters output from multiple threads may interleave, but no data races occur).
If the synchronization is turned off, the C++ standard streams are allowed to buffer their I/O independently, which may be considerably faster in some cases.
So overall, add these 2 things before the start of any program. Example:
#include<bits/stdc++.h>
using namespace std;
int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
// Your program here}