Printing a list of elements with commas in C requires a different approach compared to other languages. Here's how you can achieve this:
The difficulty in C lies in avoiding a trailing comma. In your provided code, inserting a block to add commas would introduce an additional comma at the end, which you want to avoid.
To resolve this, you can leverage an infix_iterator. Unlike a traditional output stream iterator, an infix iterator inserts a delimiter between elements, allowing you to avoid the trailing comma issue.
Using the infix_iterator:
First, include the infix_iterator.h header:
#include "infix_iterator.h"
Next, create an infix iterator and specify the delimiter you want to use (in this case, a comma):
infix_ostream_iterator<string> out_iterator(out, ",");
Finally, use the infix iterator to copy the elements from your keywords container into the output stream:
std::copy(keywords.begin(), keywords.end(), out_iterator);
This will print the elements in keywords with commas in between, and no trailing comma.
The above is the detailed content of How to Print a Comma-Separated List in C Without a Trailing Comma?. For more information, please follow other related articles on the PHP Chinese website!