Making basic for-loop to print progress bar

Hey guys,
I've had a little experience in C and now I'm taking a small class in C++. There's one project I'm working on in C++ that could have been pretty with the addition of a simple progress bar. I tried it and it didn't work. All that happens is there's a pause (since there are 1 million iterations so I can see the effect) and then the result just blurts out on the screen.

Desired result:
[==== ]20%
turns into:
[======== ]40%
and then 60, 80, and 100%.

However, all I get is:
[====================]100%
without any of the intermediary stuff. I know the "\r" overwrites it, and that's on purpose; however, there should still be enough of a pause between each percentage to see it on the screen.

What gives??

(I'm using Xcode and Terminal on my Mac.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

#define N1 1000000000
#define N2  100000000

using namespace std;

int main (void)
{
	int counter;
	
    for (counter = 0; counter < (N1+1); ++counter) {
		if ((counter / N2) == 2 && (counter % N2) == 0) {
			cout << "[====                ]20%\r";
		}
		else if ((counter / N2) == 4 && (counter % N2) == 0) {
			cout << "[========            ]40%\r";
		}
		else if ((counter / N2) == 6 && (counter % N2) == 0) {
			cout << "[============        ]60%\r";
		}
		else if ((counter / N2) == 8 && (counter % N2) == 0) {
			cout << "[================    ]80%\r";
		}
		else if ((counter / N2) == 10 && (counter % N2) == 0) {
			cout << "[====================]100%" << endl;
		}
	}
	
    return 0;
}

If you simply want it to appear to load: http://www.cplusplus.com/forum/beginner/3574/ should help.

If you want it to actually show the loading progress, then it's already doing that :)
joshjennings wrote:
All that happens is there's a pause (since there are 1 million iterations so I can see the effect) and then the result just blurts out on the screen.


That's because the std::cout buffer doesn't get flushed until the endl on line 26. Use a std::flush I/O manipulator after each "cout" and you'll get the results you expect.

http://www.cplusplus.com/reference/iostream/manipulators/flush/
Topic archived. No new replies allowed.