如何在 C/C++ 中用千位分隔符格式化数字

jst*_*rdo 7 c pocketpc windows-mobile windows-ce

我正在尝试做这个简单的任务。只是使用 C 或 C++ 格式化数字,但在 Windows CE 编程下。

在这种环境中,inbue 和 setlocale 方法都不起作用。

最后我没有成功做到这一点:

char szValue[10];
sprintf(szValue, "%'8d", iValue);
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Ric*_*ges 13

这是一种方法 - 创建自定义语言环境并为其注入适当的自定义方面:

#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';
}
Run Code Online (Sandbox Code Playgroud)

预期输出:

default locale: 123456789
locale with modified thousands: 123,456,789
Run Code Online (Sandbox Code Playgroud)

  • 更改行“auto几千=std::make_unique&lt;separate_thousands&gt;();” 到“自动千 = std::unique_ptr&lt;separate_thousands&gt;(new separate_thousands());” 对于 C++11。 (2认同)