Javatpoint Logo
Javatpoint Logo

Fast input and output in C++

In competitive programming fast execution, input and outputs matter a lot. Sometimes we need to enter only five numbers in the array and the other time there can be 10,000. These are the cases where fast I/O comes into the picture.

Fast input and output in C++

Now let us discuss some useful tips beneficial to avoid the TLE -

  • For taking a value as input, the general format in C++ is -
    std::cin>>x; // x the value to be input
    The cin works better for a range of inputs but it is convenient to use -
    scanf('%d",&x); // x is the value to be input
    Similarly, for printing on the console we use -
    Std::cout<<x ; // x is the value to be printed
    The cout also works fine for limited numbers. The best practice is using-
    printf("%d", x); // x is the value to be printed
  • To gain the same speed of scanf/printf with cin/cout. Add the below lines in the main function -
    ios_base::sync_with_stdio(false) - It toggles all the synchronization of all C++ with their respective C streams when called before cin/cout in a program. We make this function false(which is true earlier) to avoid any synchronization.
    cin. tie(NULL) - The function helps to flush all the std::cout before any input is taken. It is beneficial in interactive console programs in which the console is updated regularly but also slows down the program for larger values. NULL refers to returning a null pointer.
  • Include a header file that contains all the others libraries. It is a standard header for the GNU C++ library. Including the below header file saves time and the effort to add a particular library for a data structure. For example, for declaring a map we need a header file. This extra effort is reduced which is also time saving.
    This is how a common C++ program template looks on applying the tips:
  • It is advised to use "\n" for coming to the new line instead of endl.
    "\n" - Enters a new line
    endl - Enters a new line and flushes the stream
    cout<<endl = cout<< "\n" << flush

Differences between "\n" and endl

endl \n
Manipulator Character
Does not occupy memory Occupy memory of 1 byte
endl is a keyword. So it won't give meaning when stored in a string \n can be stored in a string
Supported only by C++ Supported by both

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA