打印带有成千上万个分隔符的整数 [英] Print integer with thousands and millions separator

查看:73
本文介绍了打印带有成千上万个分隔符的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个关于打印带有成千上万的分隔符的整数的问题。

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.

文本文件就像:

澳大利亚。 ......悉尼........................ 10.123.456

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

巴西......圣保罗.. ..... 7.123.345

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

我将全部3个读入一个单独的字符串中。然后我删除所有。在人口字符串中。然后我使用atoi()将填充字符串转换为整数。

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

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

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

x ........ x。 ..... 2.123.232

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

它看起来必须像这样:

澳大利亚..... ...悉尼......... 10.123.456

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

澳大利亚........布里斯班....... 8.123。 456

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

有没有办法通过再次添加分隔符和int来操纵打印?

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

非常感谢

推荐答案

imbue() 带有语言环境具有所需的分隔符。例如:

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

评论并回答 James Kanze 注入输入流也可以读取分隔的 int 值,而无需手动修改输入。

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

有关以下内容的详细概述,请参见Stroustrop的附录D:语言环境。语言环境。

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

这篇关于打印带有成千上万个分隔符的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆