Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 870
Reynaldo Aguilar Avatar asked Apr 15 '15 17:04

Reynaldo Aguilar


People also ask

What is the difference between cout and printf in C++?

cout is a object for which << operator is overloaded, which send output to standard output device. The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf().

Can you use printf in C++?

Answer: Yes. Printf can be used in C++. To use this function in a C++ program, we need to include the header <cstdio> in the program.

Does cout work in C?

cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.

Which is faster cout or printf?

To answer your question, printf is faster.


1 Answers

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.

like image 171
therainmaker Avatar answered Oct 11 '22 06:10

therainmaker