Printing lists with commas C++

后端 未结 28 1788
时光取名叫无心
时光取名叫无心 2020-11-22 03:33

I know how to do this in other languages, but not C++, which I am forced to use here.

I have a Set of Strings that I\'m printing to out in a list, and they need a co

28条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:01

    I use a little helper class for that:

    class text_separator {
    public:
        text_separator(const char* sep) : sep(sep), needsep(false) {}
    
        // returns an empty string the first time it is called
        // returns the provided separator string every other time
        const char* operator()() {
            if (needsep)
                return sep;
            needsep = true;
            return "";
        }
    
        void reset() { needsep = false; }
    
    private:
        const char* sep;
        bool needsep;
    };
    

    To use it:

    text_separator sep(", ");
    for (int i = 0; i < 10; ++i)
        cout << sep() << i;
    

提交回复
热议问题