Search code examples
c++consolecarriage-returnoverwrite

C++ how to overwrite a character in console, return carriage to start of line doesn't seem to work


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


Solution

  • 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.