Much of the code I write these days is for numerical methods used in physics. What I often need is some output that tells me how long a program has come in for instance a Monte Carlo integration. I had to look a bit around on the net as a regular cout command doesn’t seem to work within a loop, and I want the progress counter to overwrite the same line as it progresses. Here is the solution:
j=0;
cout << "Progress: 0%";
for(i=0; i<iMax; i++) {
//Algorithm here..
if(i%(iMax/100)==0) {
j++;
cout << "\rProgress: " << j << "%";
fflush(stdout);
}
}
cout << endl;
Key elements here are the “\r” to return the cursor to the beginning of the line (for the overwrite) and “fflush(stdout)” to flush the buffer, something which isn’t done automatically if you do not have an endl.



