So my code below removes all the numbers from a string. and each time it removes a number it goes to the next line. I want the previous lines to disappear after displaying it. I tried using system("clear") in my if loop but it did not work. how would I do this?
string sentence;
cout<<"Enter sentence: "<<endl;
cin.ignore();
getline(cin,sentence);
for(int i=0;i<sentence.length();i ) {
if(isdigit(sentence[i]))
{
sentence.erase(i, 1);
i--;
cout<<sentence;
cout<<endl;
sleep(1);
}
}
CodePudding user response:
Not a standard way to do this. But you imply Unix in your question, so this might work: use std::flush and backspaces to erase a line.
It mostly worked for me when I tried it out on Linux:
cout<<sentence << std::flush;
sleep(1);
string backspaces;
for (size_t i = 0; i < sentence.size(); i ) {
backspaces = '\b';
}
cout << backspaces << std::flush;
However, if the subsequent line is shorter than the previous line, some residual chars would remain. Might need to pad with spaces too.
You may want to investigate using the termios functions as well to see if any of that will help you.
Other options to explore include ANSI escape sequences or NCurses.
CodePudding user response:
Once the user presses Enter the cursor is already on the wrong line.
Fortunately, both Linux terminal emulators and the modern Windows Terminal should accept Esc
[
A
to move the cursor up one line. Then you can emit a carriage return to move to the beginning of the line and print out enough spaces to clear — or you could just use the clear-line code: Esc
[
K
.
void cursor_up() { std::cout << "\033[A"; }
void clear_line() { std::cout << "\033[K"; }
Neither terminal should need any magic setup to work for those two Virtual Terminal sequences.
Edit to add Thomas E Dickey’s fabulous reference as well.