Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

console application - How to get rid of left-over characters when using in C++?

Assume I have the following code which is an infinit counter :

#include <iostream>

int main() {

    short int counter = 0;

    while(true) 
        cout << "This is a counter: " << counter++ << " and I'll keep counting!
";

    return 0;
}

When you run the code with the carriage return, it will overwrite the existing text, but at the end there will be more than one '!'. Is there away to fix this without calling clear screen to avoid flickering?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Continuing from the comments above, if you are outputting to a VT compatible terminal (most are), you can use ANSI Escape sequences to control clearing to end-of-line (and various other cursor movements and visibility).

A short example working with lines terminated with a carriage-return, you can use 33[K to clear to end of line. (the formal number preceding 'K' is "0K" but can be omitted due to it being the default) The other line clearing options are "1K" clear to beginning of line, and "2K" clear entire line. You can also hide and restore the cursor with similar escapes.

In your case you can handle the additional characters from previous longer lines as:

#include <iostream>
#include <unistd.h>

int main (void) {
    
    const char *lines[] = { "You do not ever want
", 
                            "your favorite dog
", 
                            "to have
",
                            "fleas!
" };
    int n = sizeof lines / sizeof *lines;
    
    std::cout << "33[?25l";                   /* hide cursor */
    
    for (int i = 0; i < n; i++) {
        std::cout << "33[0K" << lines[i];     /* clear to end, output line */
        std::fflush (stdout);
        sleep (2);
    }
    
    std::cout << "33[?25h
";                 /* restore cursor */
}

Compile normally and run in your terminal. If it is VT compatible it will process the escapes so you see each line printed without any of the additional characters from the preceding line interfering with the output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...