从 float 到 std::string 的转换是否会受到当前系统语言环境的影响?
我想知道上面的代码是否可以在 Germal 语言环境下以“1234,5678”而不是“1234.5678”的形式产生输出,例如:
std::string MyClass::doubleToString(double value) const
{
char fmtbuf[256], buf[256];
snprintf(fmtbuf, sizeof(fmtbuf)-1, "%s", getDoubleFormat().c_str());
fmtbuf[sizeof(fmtbuf)-1] = 0;
snprintf(buf, sizeof(buf)-1, fmtbuf, value);
buf[sizeof(buf)-1] = 0;
return std::string(buf);
}
static std::string const& getDoubleFormat() { return "%f"; }
如果是,如何预防?如何始终以以下形式输出:“1234.5678”用点分隔小数点?
最佳答案
<locale>
标准 C 库的本地化影响
格式化输入/输出操作及其字符转换规则和数字格式设置中的小数点字符集。
// On program startup, the locale selected is the "C" standard locale, (equivalent to english).
printf("Locale is: %s\n", setlocale(LC_ALL, NULL));
cout << doubleToString(3.14)<<endl;
// Switch to system specific locale
setlocale(LC_ALL, ""); // depends on your environment settings.
printf("Locale is: %s\n", setlocale(LC_ALL, NULL));
cout << doubleToString(3.14) << endl;
printf("Locale is: %c\n", localeconv()->thousands_sep);
printf("Decimal separator is: %s\n", localeconv()->decimal_point); // get the point
结果是:
Locale is: C
3.140000
Locale is: French_France.1252
3,140000
Decimal separator is: ,
如果您选择 C++ 格式化函数,那么有 C++ <locale>
哪个更强大,更灵活。但是请注意,C 语言环境的设置不会影响 C++ 语言环境:
cout << 3.14<<" "<<endl; // it's still the "C" local
cout.imbue(locale("")); // you can set the locale only for one stream if desired
cout << 3.14 << " "<<1000000<< endl; // localized output
备注:
有以下问题:
static std::string const& getDoubleFormat() { return "%f"; }
该函数应返回对字符串的引用。不幸的是,您返回一个字符串文字 "%f"
这是类型 const char[3]
.这意味着有一个隐式转换将构造一个临时 string
来自const char*
并返回其引用。但是临时对象在表达式末尾被销毁,所以返回的引用不再有效!
为了测试,我按值返回。
关于c++ - Float 到 std::string 的转换和本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245824/