Is it possible on Windows without using WinAPI?
How to remove last character put to std::cout?
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
I can't seem to erase a new line with this method. –
Bituminous
Using 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. –
Cud
However, if you redirect the output to the file, then ^H and the preceding character will still be present there. –
Hertzfeld
Only works on a terminal. Breaks if you output to a pipe or a file. Won't recommend. –
Weekley
This code does exactly that:
std::cout<<"\b \b";
But if u use stringstream and compare stringstream::str() it to other strings, it won't match. This only applies to printing in the terminal –
Corpuz
Edit: Oh, so you're moving backwards, writing a space, and then moving backwards again. –
Shushan
No.
You can't without accessing the console's api that is never standard.
sorry , you can , see my answer –
Alary
© 2022 - 2024 — McMap. All rights reserved.
flush
itself before the backspace has been inserted. – Calcariferous