Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c++ - Print integer with thousands and millions separator

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 File, and sort by country. If country is eual, i have to sort descending by population.

Textfile is like:

Australia........Sydney.........10.123.456

Brazil...........Sao Paulo.......7.123.345

I read all 3 into a seperated string. Then i erase all "." in the population string. Then i use atoi() to cast the population string to an integer.

Now i can sort by population if country is equal. This sort works correctly.

So far so good. But i need to get thousand/millions seperator into the printing of the population.

If i use string,with the "." for population, sorting dont work correctly. Its sorted like:

x........x......1.123456

x........x......10.123.456

x........x......2.123.232

It have to look like:

Australia........Sydney.........10.123.456

Australia........Brisbane.......8.123.456

Is there a way to manipulate the printing by adding separator the the int again?

Many Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 << "
";

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...