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 ?
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];
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With