Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go up a line in Console Programs (C++)

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

like image 392
43.52.4D. Avatar asked Apr 07 '12 20:04

43.52.4D.


People also ask

How do you move a line up in C++?

Alt + ↑ (Up Arrow) – Moves a line up.

How do I go back to a line in CPP?

You can go to the beginning of the line by printing \r , but moving to the previous line requires platform dependent code. If don't want to use libraries like Curses, you can try ANSI escape codes. Depending on the terminal, cout << "\033[F" will move the cursor one line up.

Does cout start a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.

How do I go back to the previous line in C++?

You can go back to your previous location with the Go > Back command or Ctrl+Alt+-.


2 Answers

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.

like image 53
Greg Hewgill Avatar answered Oct 05 '22 09:10

Greg Hewgill


In windows you can use this example

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

like image 30
Vit Bernatik Avatar answered Oct 05 '22 08:10

Vit Bernatik