Difference between cout and printf

Feb 22, 2011 at 2:21pm
Hello experts,

I am new to C++. Please let me know the difference between cout and printf in functionality. I know printf was used in C (stdio.h) and cout in C++ (iostream.h)

I noticed that while using cout my output was not coming out immediately.

Regards,
Abhishek
Feb 22, 2011 at 2:38pm
cout is buffered, so the output is written only when the buffer is flushed.
Feb 22, 2011 at 2:40pm
I read it some other place too.
Can you please explain me more about how output is written and buffer flush.

Regards,
Abhishek
Feb 22, 2011 at 2:46pm
The differences are:
1) std::cout is typesafe whereas printf is not
2) std::cout natively supports user-defined types whereas printf does not

std::cout is an instantiation of an std::ostream object. std::ostream has a buffer internally to which the data is written. The buffer is flushed when either you explicitly flush it (std::flush, std::endl) or when the buffer fills. Until the buffer is flushed, you won't see the output you just wrote.
Feb 22, 2011 at 2:49pm
When you output something to cout ( or any other buffered stream ) the characters are not written directly to the destination ( eg: on the screen ) but they are stored in an internal buffer ( to improve performance since output operations are slow )
When the buffer is full or it get flushed explicitly, its contents are written to the destination and the buffer becomes empty.
Feb 22, 2011 at 2:51pm
Thanks Bazzy and Jsmith for response.

Can you give me syntax how to explicitly flush the output.

Apart from this I have one more query.

void main()
{
char i=3;
printf("%d",i);
cout<<i: //here I want to use i as integer.
}

I want to use i as integer (as in those cases where value of i will not go more than 255). It is possible in printf() using %d. How it is possible in cout.?
Feb 22, 2011 at 2:58pm
You need to cast it to an integer eg: cout << short(i);
To flush you can use the ostream member function or the manipulator:
1
2
cout.flush();
cout << flush; // you can chain this to other calls of operator<< 

http://www.cplusplus.com/reference/iostream/ostream/flush/
http://www.cplusplus.com/reference/iostream/manipulators/flush/
Feb 22, 2011 at 3:04pm
When you want to append a newline to the output you can instead use this:

cout << foo << endl;

std::endl appends the newline and flushes the stream (if it's buffered).
Topic archived. No new replies allowed.