3

How can I remove a trailing comma from the end of the line, output from an array?

for ( k = numEntries - 1; k >= i; k--)
    myArray[k] = myArray[k - 1];
myArray[i] = newValue;

for (i = 0; i < numEntries; i++) {
    cout << myArray[i];
    cout << ",";
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Fandy Tam
  • 31
  • 2
  • 2
    Really and brutally hard to do in the general case. It's easier by far to not put the comma there in the first place. There's going to be a duplicate question for this. – user4581301 Sep 11 '19 at 17:03
  • Semi-duplicate: https://stackoverflow.com/questions/3745861/how-to-remove-last-character-put-to-stdcout (semi because backspace doesn't always work) – user4581301 Sep 11 '19 at 17:04
  • Whole raft of ways to prevent writing the last delimiter: [Printing lists with commas C++](https://stackoverflow.com/questions/3496982/printing-lists-with-commas-c) – user4581301 Sep 11 '19 at 17:08

3 Answers3

3

For starters this loop

for ( k = numEntries - 1; k >= i; k--)
                          ^^^^^^
    myArray[k] = myArray[k - 1];

is incorrect. It is evident (due to this statement myArray[i] = newValue;) that you mean

for ( k = numEntries - 1; k > i; k--)
                          ^^^^^
    myArray[k] = myArray[k - 1];

As for your question then the second loop can look like

for (i = 0; i < numEntries; i++) {
    if ( i != 0 ) cout << ",";
    cout << myArray[i];
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

This is what I always use (invented as answer to a challenge question):

char const* prefix = "";
for (auto& element : myArray) {
    std::cout << prefix << element;
    prefix = ", ";
}

which is maximal compact without introducing a branch / conditional in the loop.

Carlo Wood
  • 5,648
  • 2
  • 35
  • 47
1

E.g. like this:

for (i = 0; i < numEntries; i++) {
    cout << myArray[i];
    if (i < numEntries - 1) cout << ",";
}
nielsen
  • 5,641
  • 10
  • 27