问题描述
我想将 pi 读写为 3,141592
而不是 3.141592
,因为在许多欧洲国家/地区使用逗号很常见.如何使用 iostream
s 完成此任务?换句话说
I would like to read and write pi as 3,141592
instead of 3.141592
, as using the comma is common in many European countries. How can I accomplish this with iostream
s? In other words
cout << 3.141592;
应该打印
3,141592
到标准输出.
推荐答案
您应该使用 basic_ios::imbue
来设置首选语言环境.
You should use basic_ios::imbue
to set the preferred locale.
看看这里:http://www.cplusplus.com/reference/ios/ios_base/imbue/
区域设置允许您使用用户首选的方式,因此如果意大利的计算机使用逗号分隔十进制数字,则在美国仍使用点.使用语言环境是一种很好的做法.
Locales allow you to use the preferred way by the user, so if a computer in Italy uses comma to separate decimal digits, in the US the dot is still used. Using locales is a Good Practice.
但如果您想明确强制使用逗号,请看这里:http://www.cplusplus.com/reference/locale/numpunct/decimal_point/
这是我刚刚用 g++ 制作的一个小例子,它强制使用 char ','(将分隔符作为模板参数传递只是为了好玩,并不是真正必要的)
#include <iostream>
#include <locale>
template <class charT, charT sep>
class punct_facet: public std::numpunct<charT> {
protected:
charT do_decimal_point() const { return sep; }
};
int main(int argc, char **argv) {
std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet<char, ','>));
std::cout << "My age is " << 3.1415 << " lightyears.
";
}
请注意,使用 cout.getloc()
我只覆盖当前设置的语言环境中的一个方面,也就是说,在 cout 的当前语言环境设置中,我只更改标点已完成.
do_decimal_point
是 std::numpunct
的虚函数,您可以重新定义它以提供自定义分隔符.numpunct::decimal_point
在打印您的号码时将使用此虚函数.
这篇关于如何将小数点分隔符设置为逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!