8

In C++ I'm trying to go back up a line to add some characters. Here is my code so far:

cout << "\n\n\n\n\n\n\n\n\n\n\xc9\xbb\n\xc8\xbc"<<flush;
Sleep(50);

As you can see, I have 10 newline characters. In my animation, a new block will be falling from the top of the screen. But I don't know how to go back up those lines to add the characters I need. I tried \r, but that dosen't do anything and \b dosen't go up the previous line either. Also, what exactly does flush do? I've only been programming in C++ for about 2 days so I'm a newb =P.

Thanks so much!!!

Christian

43.52.4D.
  • 950
  • 6
  • 14
  • 28

3 Answers3

16

If your console supports VT100 escape sequences (most do), then you can use ESC [ A, like this:

cout << "\x1b[A";

to move the cursor up one line. Repeat as necessary.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • I'm using Visual C++ 2010. When I use that, the console just displays a left arrow and then "[A". If I change "[A" to hex code and try it, I just get another error. What am I doing wrong? – 43.52.4D. Apr 07 '12 at 20:41
  • 1
    Oh I see, you're using Windows. VT100 escape codes work pretty much everywhere *except* Windows. Sorry about that. – Greg Hewgill Apr 07 '12 at 20:44
  • 1
    Windows doesn't really have good support for console mode programs at all. If you're just learning and don't *need* to use Windows, try installing a Linux VM and doing it there. – Greg Hewgill Apr 07 '12 at 20:47
  • @43.52.4D. if you are trying to practice c++, linux will be great for you as there are tons of readily accessible open-source libraries that you can integrate into your program. In windows you are pretty much on your own. Using existing libs is also much harder in windows. Also the gcc compiler that linux ships with gives much comprehensive error messages than vc++ making it easier to know what went wrong. – d_inevitable Apr 07 '12 at 21:11
  • On windows, you'll more than likely have to roll your own console library. Look up console buffers; they're actually *easier* to use as far as changing lines than linux, though a lot clunkier and 'hack-ish'. – Qix - MONICA WAS MISTREATED Dec 28 '12 at 12:13
  • Just saying, the link is dead. – Paghillect Aug 25 '20 at 06:20
  • @DarthPaghius: Link has been resurrected. – Greg Hewgill Aug 25 '20 at 08:11
4

In windows you can use this example

there you will create CreateConsoleScreenBuffer() and then are using SetConsoleCursorPosition(console_handle, dwPosition);

Vit Bernatik
  • 3,566
  • 2
  • 34
  • 40
0

cout will first write to internal buffer and only output it to the screen periodically and not for every character that gets inserted. This is for performance reasons.

flush tells it to empty the buffer now and show it on screen.

You should consider a library like ncurses.

d_inevitable
  • 4,381
  • 2
  • 29
  • 48