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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...