gpt4 book ai didi

c++ - 如何使 float 使用逗号而不是点?

转载 作者:可可西里 更新时间:2023-11-01 18:20:16 25 4
gpt4 key购买 nike

我想制作一个使用本地设置的运算符<<,或者如果不是,至少可以手动更改“.”的使用。小数分隔符为“,”。我会喜欢一种使流(iostream、fstream 等)执行此操作而不是创建字符串然后打印它的方法。

这可能吗?

最佳答案

您可以在您的流中注入(inject)一个 numpunct 方面。我相信这样的事情应该适合你:

template <typename T>
struct comma_separator : std::numpunct<T>
{
typename std::numpunct<T>::char_type do_decimal_point() const
{
return ',';
}
};

template <typename T>
std::basic_ostream<T>& comma_sep(std::basic_ostream<T>& os)
{
os.imbue(std::locale(std::locale(""), new comma_separator<T>));
return os;
}

int main()
{
std::cout << comma_sep << 3.14; // 3,14
}

Here is a demo.


一个较短的解决方案,它使用欧洲语言环境:

std::cout.imbue(
std::locale(
std::cout.getloc(), new std::numpunct_byname<char>("de_DE.utf8")));

但这最终取决于您的系统提供的语言环境。

关于c++ - 如何使 float 使用逗号而不是点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com