4

My question is, how do I get the numbers 10 - 0 to print out on the same line, overwriting each other using either a WIN32 or GNUC compiler in a simple manner like my code below:

This is what I have so far:

#include <iomanip>
#include <iostream>
using namespace std;

#ifdef __GNUC__
#include <unistd.h>
#elif defined _WIN32
#include <cstdlib>
#endif

int main()
{

  cout << "CTRL=C to exit...\n";

  for (int units = 10; units > 0; units--)
  {
    cout << units << '\r';
    cout.flush();
#ifdef __GNUC__
    sleep(1); //one second
#elif defined _WIN32
    _sleep(1000); //one thousand milliseconds
#endif

    //cout << "\r";// CR

  }

  return 0;
} //main

But this only prints:

10 9 8 7 6 5 4 3 2 1

CodingIsAwesome
  • 1,946
  • 7
  • 36
  • 54
  • No other libraries can be used but which I specify. There must be a way right? – CodingIsAwesome Mar 28 '11 at 00:15
  • This is pretty much an exact duplicate of: http://stackoverflow.com/questions/5451826/easy-c-loop-with-pause-but-output-is-very-weird -- In the responses Midnighter gave you a decent suggestion of how to "back up" the output stream. – debracey Mar 28 '11 at 00:28

3 Answers3

4

I did some really trivial modification (mostly just to clean it up and make it more readable):

#include <iomanip>
#include <iostream>
using namespace std;

#ifdef __GNUC__
#include <unistd.h>
#define pause(n) sleep(n)
#elif defined _WIN32
#include <cstdlib>
#define pause(n) _sleep((n)*1000)
#endif

int main()
{

  cout << "CTRL=C to exit...\n";

  for (int units = 10; units > -1; units--)
  {
    cout << setw(2) << setprecision(2) << units << '\r';
    cout.flush();
    pause(1);
  }
  return 0;
}

This worked fine with both VC++ and Cygwin. If it's not working under mingw, it sounds to me like an implementation problem.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

I recommend you use ncurses or another library for this, there is no standarized way to do it.

eordano
  • 452
  • 1
  • 5
  • 11
0

Have you tried the backspace '\b' character?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720