Forces the output buffer to release its contents.
basic_ostream<charT, traits>& flush();
The function flush() is an output only function in C++. You may use it for an immediate expulsion of the output buffer. This is useful when you have critical data or you need to ensure that a sequence of events occurs in a particular order. If the operation fails, it calls setstate(badbit).
The this pointer is returned.
Note that in the Example of basic_ostream::flush() usage: if you comment out the flush both lines will display simultaneously at the end of the program.
#include <iostream> #include <iomanip> #include <ctime> class stopwatch { private: double begin, set, end; public: stopwatch(); ~stopwatch(); void start(); void stop(); }; stopwatch::stopwatch() { using namespace std; begin = (double) clock() / CLOCKS_PER_SEC; end = 0.0; start(); cout << "begin the timer: "; } stopwatch::~stopwatch() { using namespace std; stop(); // set end cout << "\nThe Object lasted: "; cout << fixed << setprecision(2) << end - begin << " seconds \n"; } // clock ticks divided by ticks per second void stopwatch::start() { using namespace std; set = double(clock()/CLOCKS_PER_SEC); } void stopwatch::stop() { using namespace std; end = double(clock()/CLOCKS_PER_SEC); } void time_delay(unsigned short t); int main() { using namespace std; stopwatch watch; // create object and initialize cout.flush(); // this flushes the buffer time_delay(5); return 0; // destructor called at return } //time delay function void time_delay(unsigned short t) { using namespace std; time_t tStart, tEnd; time(&tStart); while(tStart + t > time(&tEnd)){}; }
Result:
begin the timer: < immediate display then pause > begin the timer: The Object lasted: 3.83 seconds