How do I rewrite a line of text in a console project? c++

后端 未结 3 1975
逝去的感伤
逝去的感伤 2020-12-17 05:54

I\'m working on a c++ console project and i would like to show a percentage without making a new line each time (so that the window doesn\'t get clogged with thousands of li

相关标签:
3条回答
  • 2020-12-17 06:28

    You can use a \r (carriage return) to return the cursor to the beginning of the line:

    This works on windows and Linux.

    From: Erase the current printed console line

    You could alternatively use a series of backspaces.

    string str="Hello!";
    cout << str;
    cout << string(str.length(),'\b');
    cout << "Hello again!";
    

    From: http://www.cplusplus.com/forum/unices/25744/

    Maybe mark as duplicate? I am really not sure how.

    0 讨论(0)
  • 2020-12-17 06:45

    This is very platform-dependent and terminal-dependent. But, you may want to look at ncurses for a start: http://linux.die.net/man/3/ncurses

    For Windows: How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?

    For Linux: https://unix.stackexchange.com/questions/43075/how-to-change-the-contents-of-a-line-on-the-terminal-as-opposed-to-writing-a-new

    0 讨论(0)
  • 2020-12-17 06:46

    A simple example that I tested on Linux would be:

    std::cout << "Some text to display..." << "\t\r" << std::flush;
    

    Here the \t adds a tabulation to handle slightly varying string lengths and \r sends the cursor back at the start of the line (as mentioned in other answers). std::flush is required to guarantee that the line is displayed without jumping to the next line.

    0 讨论(0)
提交回复
热议问题