如何设置cout语言环境以将逗号作为千位分隔符插入? [英] How do you set the cout locale to insert commas as thousands separators?
问题描述
给出以下代码:
cout << 1000;
我想要以下输出:
1,000
这可以使用std :: locale,和cout.imbue()函数,但我担心我可能在这里缺少一个步骤。你能找到吗?我目前正在复制当前语言环境,并添加一个千位分隔符facet,但逗号从不出现在我的输出中。
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;
}
推荐答案
c $ c> 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 "\03";
}
这篇关于如何设置cout语言环境以将逗号作为千位分隔符插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!