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

2020-02-29 02:10发布

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

3条回答
老娘就宠你
2楼-- · 2020-02-29 02:23

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.

查看更多
太酷不给撩
3楼-- · 2020-02-29 02:37

In windows you can use this example

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

查看更多
迷人小祖宗
4楼-- · 2020-02-29 02:47

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.

查看更多
登录 后发表回答