0

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.

Yantao Xie
  • 12,300
  • 15
  • 49
  • 79

4 Answers4

5

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
0

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

bsubrama
  • 9
  • 1
  • I know it. What I want is to delete those characters after the cursor backspaced. – Yantao Xie Jun 30 '12 at 06:23
  • To delete those characters, override them with something else... like blank spaces. – Tibi Jun 30 '12 at 06:27
  • @Tibi I know and dont want to replace them but just delete them. – Yantao Xie Jun 30 '12 at 06:36
  • You can't delete them, when you display '\b' the cursor position changes, and that's it. You need to write something to replace what was there before, so that's why you need to replace them with spaces. – Tibi Jun 30 '12 at 06:39
0

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.

kjp
  • 3,086
  • 22
  • 30
  • 1
    Different terminals are different to an extent, but this is fairly standardized (VT100 compatibility is fairly common, and ECMA-48 is more common still). There are standard alternatives to overwriting with spaces. – Dietrich Epp Jun 30 '12 at 06:47
0

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

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 2
    This has nothing to do with the operating system. The operating system is just shuffling bytes between the program and the terminal emulator. – Dietrich Epp Jun 30 '12 at 06:46