Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing using backspace control character

Tags:

c++

escaping

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 output to stdout, in case if there is another output after '\b', it becomes useless. Here is an example:

#include <iostream>

using namespace std;

int main()
{
    int a[] =  { 1, 3, 4, 5, 6, 32, 321, 9};
    for ( int i = 0; i < 8; i++) {
        cout << a[i] << "," ;
    }
    cout << "\b" ;
    //cout << endl;
    return 0;
}

In the above block of code, if the line is commented as seen, we get the desired result with no comma after the digit 9. However, if the line uncommented, the comma re-appears.

In my program, I do not want the comma to be there, but want an endline after 9. How do I do this ?

like image 943
hytriutucx Avatar asked Oct 07 '12 01:10

hytriutucx


2 Answers

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];
like image 112
nneonneo Avatar answered Sep 19 '22 20:09

nneonneo


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; });
like image 40
rici Avatar answered Sep 21 '22 20:09

rici