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.

Share:
54,770
Xirdus
Author by

Xirdus

Updated on July 27, 2022

Comments

  • Xirdus
    Xirdus almost 2 years

    Is it possible on Windows without using WinAPI?

  • rubenvb
    rubenvb over 13 years
    You do have to be careful that cout doesn't decide to flush itself before the backspace has been inserted.
  • trusktr
    trusktr about 12 years
    I can't seem to erase a new line with this method.
  • Hatoru Hansou
    Hatoru Hansou almost 9 years
    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.
  • Wojciech Migda
    Wojciech Migda over 8 years
    However, if you redirect the output to the file, then ^H and the preceding character will still be present there.
  • Hassen Dhia
    Hassen Dhia over 5 years
    sorry , you can , see my answer
  • tjysdsg
    tjysdsg about 5 years
    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
  • Andrew
    Andrew about 3 years
    Edit: Oh, so you're moving backwards, writing a space, and then moving backwards again.