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
189 views
in Technique[技术] by (71.8m points)

How do I delete a line text which has already been written on the terminal in c++?

I am currently making a Self Service Order Payment Program for a project and I was trying to figure out a way to erase the previous line of text to make it look cleaner. I discovered there was a similar function to system("CLS"); but instead of erasing all the text in the console, it only erases certain parts of the text.

I've been coding for about a week or two so if I missed anything please tell me.

switch(buy){

    case '1':
        //random code
        break;

     default:
            cout << "sorry thats not a valid number ;w;

"; //remove this text after system("pause")
            system("pause");
            system("CLS"); //I need this to remove only one line instead of the whole thing.
        
            break;
}
    
        
question from:https://stackoverflow.com/questions/65880290/how-do-i-delete-a-line-text-which-has-already-been-written-on-the-terminal-in-c

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

1 Reply

0 votes
by (71.8m points)

The s at the end of this line makes it hard to remove the text on the line using only standard control characters:

cout << "sorry thats not a valid number ;w;

"; 

Also, the system("pause"); is non-standard and will likely also result in a newline (I'm not sure about that).

What you could do is to skip the printing of and to just sleep a little before continuing.

Example:

#include <chrono>   // misc. clocks    
#include <iostream>
#include <string>
#include <thread>   // std::this_thread::sleep_for

// a function to print some text, sleep for awhile and then remove the text
void print_and_clear(const std::string& txt, std::chrono::nanoseconds sleep) {
    std::cout << txt << std::flush;      // print the text

    std::this_thread::sleep_for(sleep);  // sleep for awhile

    // Remove the text by returning to the beginning of the line and
    // print a number of space characters equal to the length of the
    // text and then return to the beginning of the line again.
    std::cout << '
' << std::string(txt.size(), ' ') << '
' << std::flush;
}

int main() {
    print_and_clear("sorry thats not a valid number...", std::chrono::seconds(1));
    std::cout << "Hello
";
}

The above will print your text, sleep for a second, then remove the text and continue. What's left on the screen after the program has executed is only Hello.


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

...