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
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().
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.
cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.
To answer your question, printf is faster.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With