Output numbers with digit grouping (1000000 as 1,000,000 and so on)

前端 未结 1 1713
刺人心
刺人心 2021-01-05 00:00

While it is easy to write something that does this by myself, I often wondered if there was something like this in iomanip or somewhere. However, I never found

1条回答
  •  天涯浪人
    2021-01-05 00:21

    According to this thread, you can set a locale on your output stream by doing something like:

    #include 
    #include 
    #include 
    
    struct my_facet : public std::numpunct {
        explicit my_facet(size_t refs = 0) : std::numpunct(refs) {}
        virtual char do_thousands_sep() const { return ','; }
        virtual std::string do_grouping() const { return "\003"; }
    };
    
    int main() {
        std::locale global;
        std::locale withgroupings(global, new my_facet);
        std::locale was = std::cout.imbue(withgroupings);
        std::cout << 1000000 << std::endl;
        std::cout.imbue(was);
    
        return 0;
    }
    

    Haven't tried it myself but it certainly sounds like a reasonable approach.

    0 讨论(0)
提交回复
热议问题