How to remove last character put to std::cout?
Asked Answered
A

4

41

Is it possible on Windows without using WinAPI?

Alas answered 19/9, 2010 at 13:31 Comment(0)
S
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

Salenasalene answered 19/9, 2010 at 13:47 Comment(5)
You do have to be careful that cout doesn't decide to flush itself before the backspace has been inserted.Calcariferous
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
A
9

This code does exactly that:

std::cout<<"\b \b";
Alary answered 12/4, 2018 at 19:23 Comment(2)
But if u use stringstream and compare stringstream::str() it to other strings, it won't match. This only applies to printing in the terminalCorpuz
Edit: Oh, so you're moving backwards, writing a space, and then moving backwards again.Shushan
L
3

No.

You can't without accessing the console's api that is never standard.

Leoleod answered 19/9, 2010 at 13:34 Comment(1)
sorry , you can , see my answerAlary
S
3

You can also use cin.get() to delete last char

Spline answered 21/11, 2019 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.