Reputation: 49
In case the title is not precisely revealing what I want to do, the following is my problem.
I want to write a c++ program in a Linux or Mac terminal to print numbers that keeps counting from 1, 2, 3 ... at the same position under a command line mode. For example, it is like displaying the number of percentage when your work is progressing(e.g. downloading something, installing software...).
I wrote a simple for-loop to print numbers and use usleep(1000);
for a delay of 1 second before printing next number. Then I use cout << "\b";
trying to move cursor back to display coming number at the same position. However I fail to create the effect that I want, the numbers are printed in a line.
I am not a skillful c++ programmer and know very limited on programming in a terminal environment. Can anyone help to give me hint or sample code for this function? Thanks!!
Upvotes: 2
Views: 2764
Reputation: 1982
This works in terminal for me (am using linux) #include #include using namespace std;
int main(int argc, char *argv[]) {
int i;
for(i=1;i<100;i++)
{
cout<<"\b\b\b"<<i;
cout.flush();
sleep(1);
}
return 0;
}
Upvotes: 0
Reputation: 7610
If you are in Linux Terminal you can also use the following code,
system("clear");
cout<<"\b";
cout<<Your_Number;
// Repeat this in a loop and call the delay function
Upvotes: 2