Hey guys!

I was writing a program that had an infinite loop, while (1) , and within that loop was an if statement checking to see if a certain amount of time had passed. If it did, it would print out something, if it didn't, it would print out a '.'. Well the message got printed out fine but the dots did not get printed until I terminated the program.

To fix it, I researched ostream and found the function flush() . Before my cout << '.' i put the flush(); statement and to my surprise it solved the problem perfectly. Why wasn't it working before? I've had this problem before and I was wondering if it's just a common programming fallacy, I'm assuming I just had something weird on the buffer but I don't know what...maybe when I cout'ed one of my strings before?


9 Years
Discussion Span
Last Post by crh0872

The program may not display the data immediately after calling cout, but hold it somewhere in memory until there is enough data to be displayed. That behavior saves a lot of time because displaying text is pretty cpu intensive. The flush() function forces the os to output the data to the output stream immediately instead of waiting for the output buffer to fill up.


Interesting, thanks for the responses...so I guess this means i should be doing

cout << ".";

not vice versa.


But the vice-versa works too because it flushes the stream anyways.
This one will do something like this :
send to buffer => flush => send to buffer => flush... and so on
while the former one would do:
flush => send to buffer => flush... and so on
Logically, the first approach (send to buffer => flush) is better than the second (flush => send to buffer)


Thanks a lot! Very helpful responses...code's working great.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.