如何将逗号设置为小数点? [英] How can I set the comma to be a decimal point?

查看:346
本文介绍了如何将逗号设置为小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读和写pi为3,141592而不是3.141592,因为它在许多欧洲国家是常见的。我如何用iostreams完成这个?换句话说,

I would like to read and write pi as 3,141592 instead of 3.141592 as it is common in many european countries. How can I accomplish this with iostreams? 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/

But if you want to explicitly force the use of the comma, take a look here: http://www.cplusplus.com/reference/locale/numpunct/decimal_point/

这里有一个小例子,我刚刚使用g ++强制执行char','(传递分隔符作为模板参数只是为了有趣,而不是真的必要)

Here a small example I just made with g++ which enforces the char ',' (passing the separator as template argument is just for fun, not really necessary)

#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.\n";
}

请注意,使用 cout.getloc code>我正在覆盖当前设置的区域设置中的一个方面,也就是说,在cout的当前区域设置中,我只改变标点符号的处理方式。

Note that using cout.getloc() I'm overriding just a single facet in the currently set locale, that is, in the current locale settings of cout, I'm changing only how the punctuation is done.

do_decimal_point std :: numpunct 的虚函数,您可以重新定义以提供自定义分隔器。在打印您的号码时, numpunct :: decimal_point 将使用此虚拟函数。

do_decimal_point is a virtual function of std::numpunct that you can redefine to provide your custom separator. This virtual function will be used by numpunct::decimal_point when printing your number.

这篇关于如何将逗号设置为小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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