Question

I want to emulate backspace in programming and implemented as below.

// del.cpp
#include <iostream>
using namespace std;

int main()
{
    cout << "123456";
    cout << "\b\b\b" /* backspace key */<< '\x7f' /* DEL key */ << '\x7f' << '\x7f';
    cout << endl;
    return 0;
}

But I get a result like this enter image description here

How can I get a result just like below without the need of replacing the tails with blank space

123

That is to say how can I delete, rather than replace, those character after the cursor which has been backspaced.

Was it helpful?

Solution

Use the "clear to end of line" escape sequence, CSI K.

cout << "123456";
cout << "\b\b\b\033[K";
cout << endl;

For a list of escape sequences, see ANSI Escape Code (Wikipedia). Of course, not all of them will work on all terminals, but these days, with software terminals, I wouldn't worry about it.

OTHER TIPS

You don't need the 0x7f after the '\b'. It is only those characters that are coming up.

There is no generic way that works in all systems for the DEL character because different terminals implement it differently. You have to go with overwriting with blank spaces if you want it to work in all terminals.

You will have to go down to your operating system API to accomplish this task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top