Text repeat on same line...

Quick question.

And I'll need the old DOS'ies out there probably to help remember what I'm talking about.

Let's say I'm 'cout'ing something (perhaps a percentage) that I want to update on a predated interval I have specified. It works perfectly in the code, but it updates on a new line (because i have it proceeded with endl).

I.e.

cout << " (" << percentage << ") completed" << endl << endl

My question is, if anyone remembers the old FORMAT command out there for DOS/WIN, do you remember how the text updated on the SAME LINE? There was no clear screen or anything, just text updating on the same line with the current percentage.

How is this done? I really didn't get a whole lot of luck searching around, because I did not know really how to ask this.

Hope someone can help!
You need to move the cursor back to the position you want to replace and output only the characters you need to refresh.
To do this only with standard stuff you shouldn't go to a new line and then use the '\b' character for each position you need to go back.
For better solutions use Windows API or Curses
So...do you have an example Bazzy? Like

1
2
3
4
cout << " (" << percentage << ") completed";
for( ...; ...; ++){
  cout << "\b\b\b\b\b"
}


Or something like that...?
1
2
3
4
5
cout << " (" << setw(3) << setfill('0') << percentage << ") completed"; // use 3 characters to represent the percentage
cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; // go back to " ("

//each time you refresh
cout << setw(3) << percentage << "\b\b\b"; // display percentage using 3 characters and go back of 3 characters  
Why thank you Bazzy.

I'll check this out and give it a shot as soon as I get a minute here.
You can also just output a carriage return '\r' to return the cursor to the beginning of the line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

#include <windows.h>

int main()
  {
  cout << endl;
  for (int n = 3; n > 0; n--)
    {
    cout << "\rWait " << n << " seconds.";
    Sleep( 1000 );
    }
  cout << "\rDone.              \n";
  return 0;
  }

Hope this helps.
Last edited on
Worked like a charm Duoas.

Oh, and no offense Bazzy, but his way seemed easier. lol
String constructors can be used with the same ease. See line 12.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

#include <windows.h>

int main()
  {
  cout << "Seconds to wait: 3.0";
  for (int n = 25; n >= 0; n -= 5)
    {
    cout << string( 3, '\b' );
    Sleep( 500 );
    cout << (n / 10) << "." << (n % 10);
    }
  cout << "\nDone.\n";
  return 0;
  }

Enjoy!
Topic archived. No new replies allowed.