Print integer with thousands and millions separator

后端 未结 2 1910
一整个雨季
一整个雨季 2020-12-11 01:41

Got a question about printing Integers with thousands/millions separator.

I got a Textfile where i got Country, City,Total Population.

I have to read in the

相关标签:
2条回答
  • 2020-12-11 02:04

    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.)

    0 讨论(0)
  • 2020-12-11 02:19

    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.

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