Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c++ - Erasing using backspace control character

I am trying to use the backspace control character '' 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 '', 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 << "" ;
    //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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The usual way of erasing the last character on the console is to use the sequence " ". 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 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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...