I do not think sync_with_stdio() is the solution here, but it explains why the use of std::cout causes stdout to be flushed. Perhaps you can try fflush(), e.g.,
By default, these standard streams are synchronized with the standard streams of C. That is, the C++ standard library ensures that the order of mixed output with C++ streams and C streams is preserved. Before any buffer of standard C++ streams writes data it flushes the buffer of the corresponding C streams and vice versa. Of course, this synchronization takes some time. If it isn't necessary you can turn it off by calling sync_with_stdio(false) before any input or output is done.