的boost :: lexical_cast的&LT的区域设置不变的保证;> [英] Locale invariant guarantee of boost::lexical_cast<>

查看:190
本文介绍了的boost :: lexical_cast的&LT的区域设置不变的保证;>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的boost :: lexical_cast的<标准::字符串>(双)双打转换为字符串,生成JSON序列化的字节流,也就是(在远程侧)由.NET解析。

我能够迫使.NET使用 InvariantCulture的解析,从而对每一个可能的语言返回predictable结果。

不过,我没能找到这个保证在<一个href=\"http://www.boost.org/doc/libs/1_54_0/doc/html/boost_lexical_cast/synopsis.html\">boost::lexical_cast文档。我试了一点点,它适用于设置不同的区域设置相同的方式。但是,我不能肯定只能从一些测试,我失去的东西的文档中,这还是不能全部guaranted,我不得不使用别的东西吗?

编辑:
我发现一个问题。

 的std ::区域::全球(性病::区域设置(捷));
性病::法院LT&;&LT;提高:: lexical_cast的&LT;标准::字符串&GT;(0.15784465)LT;&LT;的std :: ENDL;

收益 0,15784465 ,这是不需要的。我可以强制的boost :: lexical_cast的&LT;&GT; 不知道的语言环境


解决方案

  

我可以强制的boost :: lexical_cast的&LT;?>不知道的语言环境


没有,我不认为这是可能的。你能做的最好的就是调用

 的std ::区域::全球(性病::区域::经典());

在全球区域设置为C语言环境的boost :: lexical_cast的依赖于全球区域。然而,问题是,如果别的地方在code,全球区域设置为别的东西叫的boost :: lexical_cast的之前,那么你仍然有同样的问题。
因此,一个强大的解决方案将是灌输像这样一个字符串流,你可以始终确保此工作的:

 的std :: ostringstream OSS;
oss.imbue(性病::区域::经典());
OSS precision。(的std :: numeric_limits&LT;双&GT; :: digits10);
OSS&LT;&LT; 0.15784465;

I'm using boost::lexical_cast<std::string>(double) for converting doubles to string, generating JSON serialized byte stream, that is (on remote side) parsed by .NET.

I'm able to force the .NET to use InvariantCulture for parsing, thereby returning predictable result on every possible language.

However, I was not able to find this guarantee in boost::lexical_cast documentation. I tried it a little bit, and it works the same way for different locales set. But, I cannot be sure only from few tests, am I missing something in the documentation, or this cannot be guaranted at all, and I have to use something else?

EDIT: I've found an issue.

std::locale::global(std::locale("Czech")); 
std::cout << boost::lexical_cast<std::string>(0.15784465) << std::endl;

returns 0,15784465, and that is undesired. Can I force the boost::lexical_cast<> not to be aware of locales?

解决方案

Can I force the boost::lexical_cast<> not to be aware of locales?

No, I don't think that is possible. The best you can do is call

std::locale::global(std::locale::classic());

to set the global locale to the "C" locale as boost::lexical_cast relies on the global locale. However, the problem is if somewhere else in the code the global locale is set to something else before calling boost::lexical_cast, then you still have the same problem. Therefore, a robust solution would be imbue a stringstream like so, and you can be always sure that this works:

std::ostringstream oss;
oss.imbue(std::locale::classic());
oss.precision(std::numeric_limits<double>::digits10);
oss << 0.15784465;

这篇关于的boost :: lexical_cast的&LT的区域设置不变的保证;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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