How to Print a Comma-Separated List in C ?
In C , printing a comma-separated list of elements can be tricky compared to other languages like Java. To resolve this, we explore several techniques.
Using an Infix Iterator
An infix iterator allows you to insert a delimiter between each element during iteration. It's a customized variation of the standard output iterator.
// infix_iterator.h // Extended output iterator with delimiter insertion template <typename T, typename charT, typename traits = std::char_traits<charT>> class infix_ostream_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void> { std::basic_ostream<charT, traits>& os; charT const* delimiter; bool first_elem; public: infix_ostream_iterator(std::basic_ostream<charT, traits>& s) : os(&s), delimiter(0), first_elem(true) {} infix_ostream_iterator(std::basic_ostream<charT, traits>& s, charT const *d) : os(&s), delimiter(d), first_elem(true) {} infix_ostream_iterator<T, charT, traits>& operator=(T const &item) { // Insert delimiter before element unless it's the first if (!first_elem && delimiter != 0) *os << delimiter; *os << item; first_elem = false; return *this; } // ... };
Usage with Infix Iterator:
#include "infix_iterator.h" // ... // Copy elements using infix iterator to insert commas std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));
The above is the detailed content of How to Efficiently Print Comma-Separated Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!