Comma-Separated List of Elements in C
In C , printing a list of strings (keywords) with commas between each element, but excluding a trailing comma, can be achieved through an infix_iterator. This iterator provides a convenient method to achieve the desired output.
The infix_ostream_iterator class, defined in the infix_iterator.h header file, extends the standard ostream_iterator by inserting a customizable delimiter between elements. The constructor of this class takes an ostream reference and an optional delimiter string.
To use this iterator, you can specify the delimiter when constructing the infix_ostream_iterator object. The overridden assignment operator checks if it's not the first element and inserts the delimiter before printing the item to the stream.
Here's an example code snippet demonstrating how to use this iterator:
#include "infix_iterator.h" auto iter = keywords.begin(); infix_ostream_iterator out(std::cout, ","); std::copy(iter, keywords.end(), out);
This code will print the keywords from the keywords container, separated by commas, without a trailing comma. The result will be printed to the standard output.
By employing the infix_ostream_iterator, you can easily and efficiently print comma-separated lists in C without having to manually manage comma insertion and deletion.
The above is the detailed content of How to Print Comma-Separated Lists in C Without a Trailing Comma?. For more information, please follow other related articles on the PHP Chinese website!