Erasing using backspace control character

后端 未结 4 584
一个人的身影
一个人的身影 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 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

提交回复
热议问题