Print integer with thousands and millions separator

喜你入骨 提交于 2019-11-29 09:35:05
hmjd

imbue() the output stream with a locale that has the desired separator. For example:

#include <iostream>
#include <locale>

int main()
{
    // imbue the output stream with a locale.
    int i = 45749785;
    std::cout << i << "\n";

    std::cout.imbue(std::locale(""));
    std::cout << i << "\n";
}

Output on my machine (and online demo):

45749785
45,749,785

As commented, and answered, by James Kanze imbue the input stream also to read the separated int values without manually modifying the input.


See Stroustrop's Appendix D: Locales for a detailed overview of locales.

Use a locale which supports the desired separators to read the file (that way you can read the values as integers), and the same locale to write the data.

Note that you may not have such a locale available, or if you do, you may not know its name (and using a named locale might change other things, that you don't want changed); on my machine, imbueing with "" behaves differently according to the compiler (or maybe the shell I'm invoking it from)—you should never use the locale "" if you have strict formatting requirements. (The use of locale "" is for the case when you want the format to depend on the users environment specifications.)

In this case, it's probably better to provide the local explicitly:

class MyNumPunct : public std::numpunct<char>
{
protected:
    virtual char do_thousands_sep() const { return ','; }
    virtual std::string do_grouping() const { return "\03"; }
};

int
main()
{
    std::cout.imbue( std::locale( std::locale::classic(), new MyNumPunct ) );
    std::cout << 123456789 << std::endl;
    return 0;
}

Of course, you'll want to use this locale for the input as well. (This code will give you the "C" locale, with only the grouping changed.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!