Some tips for using cin, cout and endl in cpp

Revision en1, by VCodes_07, 2024-06-25 20:23:41

Here's the detail: cin is by default tied to cout. This means that whenever you input (cin) something, your program checks whether your output buffer is empty or not. If not, it prints or "flushes" the buffer. This check or flushing is slow can sometimes cause your program to TLE.

How to make cin and cout faster? By using fastio. cin.tie(nullptr) breaks the tie between cin and cout and so your program doesn't check the buffer when you input. This makes your code faster.

However, be careful while using fastio in interactive problems In interative problems, you don't get all the input before the outputs. Because of this, you need to flush your buffer. There are two main ways of solving this issue. 1) Don't use fastio for interactive problems. 2) Use fastio but flush your outputs with the help of endl. endl does two things. It prints a newline like '\n' does. Secondly, it also flushes the output. NOTE: Please make sure not to use '\n' with fastio if you want to flush your output.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English VCodes_07 2024-06-25 20:23:41 1062 Initial revision (published)