Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 << ",";
}
like image 468
Fandy Tam Avatar asked May 31 '26 23:05

Fandy Tam


1 Answers

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];
}
like image 185
Vlad from Moscow Avatar answered Jun 02 '26 11:06

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!