How to erase a printed, on the screen, character

Lets say I print on the screen the word "deleted", but I want to make it "delete". How can I delete the character 'd'?
I tried using the escape character backspace '\b', but it just moved the cursor(invisible ofcourse) a character to the left.

Here's what I did:
1
2
3
4
5
6
7
8
#include<iostream>
using namespace std;
int main(){
cout<<"deleted";
cout<<"\b";

return 0;
}

It printed: deleted

Then I did this:
1
2
3
4
5
6
7
8
#include<iostream>
using namespace std;
int main(){
cout<<"deleted";
cout<<"\b ";     //backspace and a space character " "

return 0;
}

It printed: delete

Then I did this:
1
2
3
4
5
6
7
8
#include<iostream>
using namespace std;
int main(){
cout<<"deleted";
cout<<"\b\b\b ";     //three backspaces and a space

return 0;
}

It printed: dele ed

Thus I came to the conclusion that backspace simply moves the cursor to the left. How can I delete a character and not just replace it with a space?
Hello orestisman,

Based on your last example I would try std::cout << "\b\b\b \b\b\b . Backspace three times print three spaces backspace three spaces to put the cursor where it should be. The simple way, there might be better way that I am not familiar with.

Hope that helps,

Andy
Last edited on
std::cout is a stream (See https://en.wikipedia.org/wiki/Stream_(computing) ).
Things that are written to a stream leave your control as soon as they're consumed, so removing things from that stream just doesn't make sense.

Of course, a stream is not your terminal, and in an interactive context, it's the job of the terminal (not of your program) to display the contents of that stream as it become available. Part of this job includes interpreting backspaces as it sees fit.

The point of this: if you need to control a terminal as if it was a screen, use a library like ncurses, or be judicious about it.
When you run your program interactively, doing std::cout << "hello worls\bd\n";prints
hello world
But if you redirect your program's output to a file (./program > file), that file will not merely contain
hello world
It will contain some extra bytes:
hello worls\bd\n
Which might change the meaning.

If your only concern is using this program interactively, probably Handy Andy has got the solution ;).
Last edited on
Topic archived. No new replies allowed.