Locale invariant guarantee of boost::lexical_cast<>

后端 未结 2 700
粉色の甜心
粉色の甜心 2021-01-18 03:48

I\'m using boost::lexical_cast(double) for converting doubles to string, generating JSON serialized byte stream, that is (on remote side) par

2条回答
  •  醉梦人生
    2021-01-18 04:28

    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::digits10);
    oss << 0.15784465;
    

提交回复
热议问题