Erasing using backspace control character

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


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; });

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];

Tags:

C++

Escaping