CPP - Decoupling the I/O streams

April 18, 2026

Streaming Data

The C++ standard library provides the basic functionally to input and output data. There are also C style stream input/output operations that are implemented within this library.

C++ streams: cin, cout, cerr, clog, wcin, wcout, wcerr, wclog
C streams: stdin stdout stderr

Let's Decouple

Normally, both the C++ and C streams are synchronized. This means you can safely mix C++ style and C style input/output code. The result on screen will be in the expected order. This will be the order they are written, as seen in the following example.

                
  #include <iostream>
  #include <stdio.h>

  using namespace std;

  int main() 
  {
      cout << "Hello "; // C++ output
      printf("World!"); // C output
      return 0;
  }
                
            

Output:

   Hello World!



                
  ios_base::sync_with_stdio(false)
                
            

This change will disable the synchronisation between the C++ and C streams. The C++ streams will have access to another buffer. This means that the order of input/output between the two languages will no longer be guaranteed. In practice, it means that our previous example result may become 'World! Hello', depending on which compiler is used. For this reason, it would be wise to stick to the C++ style input/output with this change.

Be aware

Thread-safety is lost with this change.



By default, the input and output streams are tied together. This means that the output stream (cout) will be flushed every time an input stream (cin) instruction is executed.

                
  cin.tie(NULL);
                
            

This line of code will untie the input and output streams. The synchronisation between the streams will be turned off. This change can benefit a section of code that it repeatedly reading and writing small bits of data many times.

Remember

Make sure these changes are done before any input/output code.

                
  int main()
  {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);

      // C++ style I/O code here

      return 0;
  }
                
            

Be mindful

Both of these changes may provide a speed improvement for a project with a large code base. However, it is important to keep in mind the side effects when you commit to these changes.