Flush cout output carefully

shabbir's Avatar author of Flush cout output carefully
This is an article on Flush cout output carefully in C++.
When you compile the following code in VS 6 you get the output as

Code: cpp
#include <iostream.h>
#include <stdio.h>
void main()
{
  cout<<"hello";
  printf("hi");
}
hihello

The reason behind this is cout is not flushed and you can get the desired out put by doing
Code: cpp
#include <iostream.h>
#include <stdio.h>
void main()
{
  cout<<"hello";
  flush(cout);
  printf("hi");
}
You can also use the <<endl; to flush the output after each cout but keep in mind that flushing the output can degrade performance.

Thanks
Shabbir Bhimani
0
AhmedHan's Avatar, Join Date: Oct 2005
Go4Expert Member
Wov, that's really interesting.

In which header flush() is defined in? stdio.h or iostream.h?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by AhmedHan
Wov, that's really interesting.

In which header flush() is defined in? stdio.h or iostream.h?
Both.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
I might mention that iostream.h is deprecated and is provided for backward compatibility. One should use iostream without an extension. The phenomenon occurs because cout and printf use two different streams; they may, however, be synced. It is generally not good practice to mix the two forms.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Forgot to mention that "void main" is non-standard code. The standard specifies that main return an int. Some compilers, particularly less compliant ones, accept the void specification, but its use is non-standard and not recommended practice.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by DaWei
I might mention that iostream.h is deprecated and is provided for backward compatibility. One should use iostream without an extension. The phenomenon occurs because cout and printf use two different streams; they may, however, be synced. It is generally not good practice to mix the two forms.
Quote:
Originally Posted by DaWei
Forgot to mention that "void main" is non-standard code. The standard specifies that main return an int. Some compilers, particularly less compliant ones, accept the void specification, but its use is non-standard and not recommended practice.
Both the points well accepted.
0
rahul.mca2001's Avatar, Join Date: Feb 2008
Ambitious contributor
i will try to use flush now
0
msdnguide's Avatar, Join Date: May 2011
Go4Expert Member
does <<endl; really flush the buffer? I seriously doubt coz putting \n in printf does not. then how can endl do that