Synchronizing streams

I read this code on internet and I have no idea why the output is b a c
Why does sync_with_stdio() do?
The article said that it synchronizes C++ streams with C streams. what does that mean and what is It used for?
1
2
3
4
5
6
7
8
9
 #include <iostream> 
#include <cstdio>   
int main()
 { 
std::cout.sync_with_stdio(false); 
std::cout << "a\n"; 
std::printf("b\n"); 
std::cout << "c\n";
 }
Last edited on
The call to sync_with_stdio() allows or in this case doesn't allow the c++ streams (cout) to sync its output with the "C" library.

The output is b a c because stdout and cout are not synchronized (since the code passed false to sync_with_stdio(). So, stdout prints before the cout stream. I think the order is implementation-dependent.
Last edited on
Setting sync_with_stdio() to false causes the C-stdio functions and the C++ streams to use separate buffers. The reason you're seeing the output you do is because you're not flushing your cout stream until the program ends but you are flushing the C-stdio stream. If you were to use endl instead of the '\n' you should see a b c.

Remember the '\n' character doesn't cause a C++ stream to flush.


Topic archived. No new replies allowed.