Is it possible on Windows without using WinAPI?
Asked
Active
Viewed 6.2k times
4 Answers
98
You may not remove last character.
But you can get the similar effect by overwriting the last character. For that, you need to move the console cursor backwards by outputting a '\b' (backspace) character like shown below.
#include<iostream>
using namespace std;
int main()
{
cout<<"Hi";
cout<<'\b'; //Cursor moves 1 position backwards
cout<<" "; //Overwrites letter 'i' with space
}
So the output would be
H

bjskishore123
- 6,144
- 9
- 44
- 66
-
6You do have to be careful that cout doesn't decide to `flush` itself before the backspace has been inserted. – rubenvb Sep 19 '10 at 16:47
-
3I can't seem to erase a new line with this method. – trusktr Mar 24 '12 at 22:00
-
1Using backspace character is actually multi-platform as I had tested it on Linux and it works. To do "console animations" like progress bars, first disable buffering in std::cout by adding this at the start of main function std::cout << unitbuf; Now printing a '\b' will remove a char in the real console, not in the std::cout internal buffer. I don't know if std::cout buffers the '\b' or interprets it and delete a character from its internal buffer when buffering is on. – Hatoru Hansou Jul 14 '15 at 16:10
-
2However, if you redirect the output to the file, then ^H and the preceding character will still be present there. – Wojciech Migda Aug 18 '15 at 13:28
9
This code does exactly that:
std::cout<<"\b \b";

buggy
- 23
- 6

Hassen Dhia
- 555
- 4
- 11
-
3But if u use stringstream and compare stringstream::str() it to other strings, it won't match. This only applies to printing in the terminal – tjysdsg Apr 18 '19 at 16:10
-
1Edit: Oh, so you're moving backwards, writing a space, and then moving backwards again. – Andrew May 03 '21 at 02:48