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?

Thanks

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.

so, flush() is different from cin.sync();cin.clear() ?

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

cout << ".";
cout.flush();

not vice versa.

Yes.
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)

Another option is: cout << "." << flush();

Member Avatar for jencas

Another option is: cout << "." << flush();

..but without the () behind flush!

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.