Home > front end >  C : Backspace characters not showing in stdout?
C : Backspace characters not showing in stdout?

Time:09-28

I am implementing a shell that has command history. When the user presses the up or down arrow, the text in the current line is replaced with the previous or next command.

The algorithm I'm planning on implementing is fairly simple. If the current command has k characters, I output k '\b' characters to delete the k characters int he current line and then output the selected command to the line.

However, I'm trying to start out with something basic, such as seeing if outputting '\b' characters even works in deleting characters from the current stdout line:

#include <iostream>
#include <queue>
#include <deque>
#include <string>

using namespace std;

int main(int argc, char *argv[]){
    cout << "asdf";
    cout << "\b\b" << endl;
    return 0;
}

The output of the above piece of code is:

asdf

When I expect:

as

Important: I want to delete characters after they are outputted to stdout.

CodePudding user response:

You need ANSI escape codes. Try:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[]){
    cout << "asdf";
    cout<<"\b\b\b\b\033[J";
    return 0;
}

\033 stands for ESC and [J is a parameter to the code. ESC[J clears the screen from the cursor to the end of the screen. For more information: https://en.wikipedia.org/wiki/ANSI_escape_code#Fe_Escape_sequences

As @n. 1.8e9-where's-my-share m. mentioned, \b simply moves the cursor back one space, and does not rewrite anything, for most implementations.

CodePudding user response:

I recommend to use ncurses and readline libraries.

Example:

sudo apt-get install libncurses5-dev libncursesw5-dev libreadline-dev
git clone https://github.com/ulfalizer/readline-and-ncurses
cd readline-and-ncurses 
make
rlncurses

My environment:

lsb_release -d ; uname -r ; g   --version | head -1
Description:    Ubuntu 20.04.3 LTS
4.4.0-19041-Microsoft
g   (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
  • Related