Erasing using backspace control character

后端 未结 4 562
一个人的身影
一个人的身影 2020-12-02 19:09

I am trying to use the backspace control character \'\\b\' to erase trailing commas at the end of line. Although it works in cases where there is no other outpu

相关标签:
4条回答
  • 2020-12-02 19:49

    The usual way of erasing the last character on the console is to use the sequence "\b \b". This moves the cursor back one space, then writes a space to erase the character, and backspaces again so that new writes start at the old position. Note that \b by itself only moves the cursor.

    Of course, you could always avoid outputting the comma in the first place:

    if(i > 0) cout << ",";
    cout << a[i];
    
    0 讨论(0)
  • 2020-12-02 19:51

    Or, if you're fond of C+11 hacks:

    adjacent_difference(a.begin(), a.end(), ostream_iterator<int>(std::cout),
      [](int x, int)->int { return std::cout << ",", x; });
    
    0 讨论(0)
  • 2020-12-02 20:08

    yeah the \b will only move the curse so when you end the line it just moves it back to the end of the line. so to actually erase the last part have a space after \b to actually erase the last comma. example: cout<<"\b ";

    0 讨论(0)
  • 2020-12-02 20:09

    Using backspace escape sequence leads to minor issue. If you want to print your array and you've defined it up front - its size is always non zero. Now imagine that you do not know size of your array, set, list or whatever you want to print and it might be zero. If you've already printed sth. before printing your stuff and you are supposed to print zero elements your backspace will devour something already printed.

    Assume you are given pointer to memory location and number of elements to print and use this ...:

    void printA(int *p, int count)
    {
        std::cout << "elements = [";
    
        for (int i = 0; i < count; i++)
        {
            std::cout << p[i] << ",";
        }
    
        std::cout << "\b]\n";
    }
    

    ...to print:

    int tab[] = { 1, 2, 3, 4, 5, 6 };
    
    printA(tab, 4);
    printA(tab, 0); // <-- a problem
    

    You end up with:

    elements = [1,2,3,4]
    elements = ]
    

    In this particular case your opening bracket is 'eaten'. Better not print comma after element and delete last one since your loop may execute zero times and there is no comma to delete. Instead print comma before - yes before each element - but skip first loop iteration - like this:

    void printB(int *p, int count)
    {
        std::cout << "elements = [";
    
        for (int i = 0; i < count; i++)
        {
            if (i != 0) std::cout << ',';
            std::cout << p[i];
        }
    
        std::cout << "]\n";
    }
    

    Now this code:

    printB(tab, 4);
    printB(tab, 0);
    

    generates this:

    elements = [1,2,3,4]
    elements = []
    

    With backspace esc. seq. you just never know what you might delete.

    working example

    0 讨论(0)
提交回复
热议问题