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

ⅰ亾dé卋堺 提交于 2019-12-03 21:09:57

问题


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


回答1:


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.




回答2:


In windows you can use this example

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




回答3:


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.



来源:https://stackoverflow.com/questions/10058050/how-to-go-up-a-line-in-console-programs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!