如何在C/C ++中使用千位分隔符格式化数字 [英] How to format a number with thousands separator in C/C++

查看:687
本文介绍了如何在C/C ++中使用千位分隔符格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成此简单任务.只是要使用C或C ++格式化数字,但要在Windows CE编程下进行.

I am trying to do this simple task. Just to format a number using C or C++, but under Windows CE programming.

在这种环境下,inbue或setlocale方法均无效.

In this environment, neither inbue nor setlocale methods work.

最后,我这样做没有成功:

Finally I did this with no success:

char szValue[10];
sprintf(szValue, "%'8d", iValue);

有什么主意吗?

推荐答案

这里是一种方法-创建自定义语言环境,并使用适当自定义的方面对其进行赋值:

Here's one way - create a custom locale and imbue it with the appropriately customised facet:

#include <locale>
#include <iostream>
#include <memory>

struct separate_thousands : std::numpunct<char> {
    char_type do_thousands_sep() const override { return ','; }  // separate with commas
    string_type do_grouping() const override { return "\3"; } // groups of 3 digit
};

int main()
{
    int number = 123'456'789;
    std::cout << "default locale: " << number << '\n';
    auto thousands = std::make_unique<separate_thousands>();
    std::cout.imbue(std::locale(std::cout.getloc(), thousands.release()));
    std::cout << "locale with modified thousands: " << number << '\n';
}

预期输出:

default locale: 123456789
locale with modified thousands: 123,456,789

这篇关于如何在C/C ++中使用千位分隔符格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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