How do you set the cout locale to insert commas as thousands separators?(你如何设置 cout 语言环境来插入逗号作为千位分隔符?)
问题描述
给定以下代码:
cout << 1000;
我想要以下输出:
1,000
这可以使用 std::locale 和 cout.imbue() 函数来完成,但我担心我可能会在这里遗漏一步.你能发现吗?我目前正在复制当前语言环境,并添加千位分隔符方面,但逗号从未出现在我的输出中.
This can be done using std::locale, and the cout.imbue() function, but I fear I may be missing a step here. Can you spot it? I'm currently copying the current locale, and adding a thousands separator facet, but the comma never appears in my output.
template<typename T> class ThousandsSeparator : public numpunct<T> {
public:
ThousandsSeparator(T Separator) : m_Separator(Separator) {}
protected:
T do_thousands_sep() const {
return m_Separator;
}
private:
T m_Separator;
}
main() {
cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));
cout << 1000;
}
推荐答案
do_thousands_sep
的默认实现已经返回','
.看起来您应该改写 do_grouping
.do_grouping
默认返回一个空字符串,表示没有分组.这意味着每组三位数字:
The default implementation of do_thousands_sep
already returns ','
. It looks like you should override do_grouping
instead. do_grouping
returns an empty string by default, which means no grouping. This means groups of three digits each:
string do_grouping() const
{
return " 3";
}
这篇关于你如何设置 cout 语言环境来插入逗号作为千位分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何设置 cout 语言环境来插入逗号作为千位分隔符?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01