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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 00:36:09364browse

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

Printing Elements in a Comma-Separated List

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!

Statement:
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