简体   繁体   中英

Backspace \b not working for the end of string

So essentially I want to create a backspace program that removes the carrot key and the character before the carrot key ( < ).

For example, let's say I have the string: a<b<cd
This would output: cd
The carrots are essentially backspace.

My issue is when I have the carrot key at the end: the terminal completely disregards it and moves the cursor to the left rather than backspacing it.

Why does it only do it for the end and not for characters in the middle?

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>

int main() {
    std::string messystr = "a<a<a<aa<<";
    int count = 0;
    for (int i = 0; i < messystr.length(); i++) {
        if (messystr[i] == '<') {
            messystr[i] = '\b';
        }
    }
    std::cout << messystr << std::endl;
}       

The output should be nothing but the terminal outputs one a .

As you know characters such as '\b', '\n', ... are considered as escape sequences, and this very specific type ('\b') is named backspace, but it would not work as the way you might think. When we use \b in our string, we are not telling the std::cout object to remove the character, we are simply telling it to move the cursor back one position, and if we write something after \b, then we are going to overwrite the character before the \b. Let me show an example "s": is simply "s", with the cursor at the end of the string "s\b": it is also simply an "s", but with the cursor at the start of the string, not after s."s\ba": is "a", and the s gets deleted because we write s, then we movethe cursor before s, and then 'a' overwrites 's' and we are left with "a".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM