Reputation: 31
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
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
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
Reputation: 7719
E.g. like this:
for (i = 0; i < numEntries; i++) {
cout << myArray[i];
if (i < numEntries - 1) cout << ",";
}
Upvotes: 1