Reynaldo Aguilar
Reynaldo Aguilar

Reputation: 1936

Why doesn't this code using printf and cout have the expected output?

I have the following code:

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

    for (int i = 0; i < 3; i++) {
        cout << i << " ";
        printf("%d ", i);
    }

    cout << endl;
    return 0;
}

The expected output of this code is:

0 0 1 1 2 2

but, instead, it prints:

0 1 2
0 1 2

This issue happens in GNU G++ 4.9.2 compiler

Upvotes: 15

Views: 1748

Answers (5)

ALXGTV
ALXGTV

Reputation: 362

By default the C stdio functions printf, etc. and the C++ io streams are synchronized meaning they can be used interchangeably. At the beginning of your code you have removed the synchronization with ios_base::sync_with_stdio(false) not sure if your actual intent was to write this ios_base::sync_with_stdio(true) which synchronizes the two io libraries.

Upvotes: 9

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You probably miss to flush() std::cout. printf() has a different behavior regarding this. Also the IO buffers should be synchronized. If you change your code to

int main () {
    ios_base::sync_with_stdio(true); // Synchronizing the IO buffers
                                     // must be enabled
    cin.tie(NULL);    

    for (int i = 0; i < 3; i++) {
        cout << i << " ";
        cout.flush(); // <<<<<<<<<<
        printf("%d ", i);
    }

    cout << endl;
    return 0;
}

it should behave as you expected. See the working demo here please.

Upvotes: 1

itachi
itachi

Reputation: 302

Try this

    cout << i << " " <<std::flush;
    printf("%d ", i);
    fflush(stdout);

Upvotes: 5

therainmaker
therainmaker

Reputation: 4343

One possible explanation for this is that cout and printf use separate buffers. cout outputs on the terminal screen either when it is flushed using the endl command, or if the buffer is full (generally 512 bytes).

I am not sure about printf (so feel free to correct me if I'm wrong), but it also follows a similar behaviour. So what happens is that at the end of the program, both the buffers are flushed, and so the output you see is achieved.

I ran the code on my machine (GCC 4.8.1) along with the modification as below

cout << i << " . ";
printf("%d ", i);

The output I observed was 0 1 2 0 . 1 . 2 . which seems to indicate that printf flushes first in my case. I have no idea if it is by design (mentioned somewhere in the standard), or if it depends on the context.

Upvotes: 12

R Sahu
R Sahu

Reputation: 206567

If you want the output std::cout and printf to be sync'ed, you'll need to use:

std::ios_base::sync_with_stdio(true);

not

std::ios_base::sync_with_stdio(false);

See it working at http://ideone.com/7sgH2I.

Upvotes: 3

Related Questions