开发者

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


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.


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


Have you tried the backspace '\b' character?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜