Fandy Tam
Fandy Tam

Reputation: 31

Remove trailing comma in C++

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 << ",";
}

Upvotes: 3

Views: 1340

Answers (3)

Carlo Wood
Carlo Wood

Reputation: 6811

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.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

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

Upvotes: 3

nielsen
nielsen

Reputation: 7719

E.g. like this:

for (i = 0; i < numEntries; i++) {
    cout << myArray[i];
    if (i < numEntries - 1) cout << ",";
}

Upvotes: 1

Related Questions