Difference between cout and printf

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
cout is buffered, so the output is written only when the buffer is flushed.
I read it some other place too.
Can you please explain me more about how output is written and buffer flush.

Regards,
Abhishek
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.
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.
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.?
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/
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.