Home > Backend Development > C++ > How to Print Comma-Separated Lists in C Without a Trailing Comma?

How to Print Comma-Separated Lists in C Without a Trailing Comma?

Susan Sarandon
Release: 2024-12-25 21:04:09
Original
413 people have browsed it

How to Print Comma-Separated Lists in C   Without a Trailing Comma?

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template