Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Flush cout output carefully (http://www.go4expert.com/articles/flush-cout-output-carefully-t378/)

shabbir 6Jul2005 12:53

Flush cout output carefully
 
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

AhmedHan 18Oct2005 19:35

Re: Flush cout output carefully
 
Wov, that's really interesting.

In which header flush() is defined in? stdio.h or iostream.h?

shabbir 18Oct2005 19:59

Re: Flush cout output carefully
 
Quote:

Originally Posted by AhmedHan
Wov, that's really interesting.

In which header flush() is defined in? stdio.h or iostream.h?

Both.

DaWei 7Dec2006 21:33

Re: Flush cout output carefully
 
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.

DaWei 7Dec2006 21:36

Re: Flush cout output carefully
 
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.

shabbir 8Dec2006 10:23

Re: Flush cout output carefully
 
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.

rahul.mca2001 6Mar2008 13:52

Re: Flush cout output carefully
 
i will try to use flush now

msdnguide 27May2011 20:19

Re: Flush cout output carefully
 
does <<endl; really flush the buffer? I seriously doubt coz putting \n in printf does not. then how can endl do that


All times are GMT +5.5. The time now is 18:51.