-
Using flush command.
Hi,
I am a newbie at C++.
I've made my first program in C++.
It's quite small, 181 lines of code in fact :)
I finally got it to compile and run successfully :)
The thing is, I had to use the flush command very often.
Without them, the program wasn't running well :(
Here is an example of what I was using:
cout<<"text"<<flush;
My question is, is there a certain pattern that I must use for the flush command? In other words, when do I have to use it?
I found that I never know exactly when to use it, in fact, I had to keep trying it in different places until it finally worked well.
Any ideas? :) :)
Marc
-
Using cout you are dealing with buffered I/O which basically means that your code is not the thing making the decision as to when stuff you have sent to be output will actually be displayed. When you write something to the screen using cout many people would expect that the data goes right to the screen immediately. What really happens is that all of this output goes to a buffer and the data held in that buffer only gets sent to the screen once it is full. So, if you do something like asking the user for input using cout and you haven't flushed the buffer, then the user may see a blank screen because the output buffer is not full and the information you wanted to be displayed is sitting in the buffer waiting for it to get full. You can easily avoid this by outputting an endl at the end of all your cout statements since this automatically flushes the buffer along with printing out a new line.
Code:
cout << "Hello there!" << endl; // Buffer flushed automatically
Hopefully this gives you some understanding, however minimal, of what's going on and helps in some way.