How to remove last character put to std::cout?
54,770
Solution 1
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
Solution 2
This code does exactly that:
std::cout<<"\b \b";
Solution 3
You can also use cin.get()
to delete last char
Solution 4
No.
You can't without accessing the console's api that is never standard.
Author by
Xirdus
Updated on July 27, 2022Comments
-
Xirdus almost 2 years
Is it possible on Windows without using WinAPI?
-
rubenvb over 13 yearsYou do have to be careful that cout doesn't decide to
flush
itself before the backspace has been inserted. -
trusktr about 12 yearsI can't seem to erase a new line with this method.
-
Hatoru Hansou almost 9 yearsUsing 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.
-
Wojciech Migda over 8 yearsHowever, if you redirect the output to the file, then ^H and the preceding character will still be present there.
-
Hassen Dhia over 5 yearssorry , you can , see my answer
-
tjysdsg about 5 yearsBut if u use stringstream and compare stringstream::str() it to other strings, it won't match. This only applies to printing in the terminal
-
Andrew about 3 yearsEdit: Oh, so you're moving backwards, writing a space, and then moving backwards again.