top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Optimising C++ Streams - cin, cout , cerr and clog

+1 vote
608 views

Generally (by default), the iostream standard stream objects - cin, cout, cerr, clog, and their wide character alternatives wcin, wcout, wcerr and wclog, are synchronized with C standard streams : stdin, stdout and stderr.

This synchronisation is an performance overhead for pure C++ modules.
With stdio synchronization turned off, iostream stream objects may operate independently of the standard C streams.

To control this behavior C++ provides below static method -

  public static member function
  ios_base::sync_with_stdio
  bool sync_with_stdio ( bool sync = true );

---- Toggles on or off synchronization of the iostream standard streams with the standard C streams.

Notice that this is a static member function, therefore a call to this function using the member of any object (or of any related class) toggles on or off synchronization for all standard iostream objects.

 std::ios_base::sync_with_stdio(false);

This will increase program speed in linux not much difference in windows.

One can also consider untie cin with cout (after calling sync_with_stdio with false).

 std::cin.tie(0);

cin is usually tied with cout to provide a intuitive way to code cli like program, where the cin prompt is preceded with some text which suggest what to input.

for e.g.

 std::string name; 
 cout << "Enter Name: ";
 cin >> name;

(for further reading)

posted Sep 23, 2014 by Sumit Jindal

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...