C++ 浮点到std::字符串转换和本地化
从float到std::string的转换是否会受到当前系统区域设置的影响 我想知道上述代码是否可以在Germal locale下以“12345678”而不是“1234.5678”的形式生成输出,例如:C++ 浮点到std::字符串转换和本地化,c++,decimal,locale,C++,Decimal,Locale,从float到std::string的转换是否会受到当前系统区域设置的影响 我想知道上述代码是否可以在Germal locale下以“12345678”而不是“1234.5678”的形式生成输出,例如: std::string MyClass::doubleToString(double value) const { char fmtbuf[256], buf[256]; snprintf(fmtbuf, sizeof(fmtbuf)-1, "%s", getDoubleForm
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”的形式输出,并用点分隔小数?标准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
如果你选择C++的格式化函数,那么有强的和强的<强> <强>。注意,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
函数应返回对字符串的引用。不幸的是,您返回了一个字符串literal“%f”
,其类型为const char[3]
。这意味着存在一个隐式转换,该转换将从常量char*
构造一个临时字符串
,并返回其引用。但是临时对象在表达式末尾被销毁,因此返回的引用不再有效
对于测试,我返回了值 web的答案是:]是的,它依赖于区域设置,因此为了防止这种更改,请使用类似的区域设置。如果使用c++11,请使用std::to_string等
std::to_string
函数是否与语言环境无关?不管当前的语言环境设置如何,它是否总是以“1234.5678”的形式返回double?To_字符串也依赖于语言环境。但是它摆脱了典型的snprintf混乱,完全取代了doubleToString,因此它绝对值得使用。例如,我不明白为什么locale不是std::to_string
的参数。在多线程环境中,如果上面的函数使用setLocale()
和restoreLocale()
包装,那么我的应用程序的其他部分也会受到此区域设置更改的影响…POSIX允许您更改每个线程的区域设置,请参阅
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"; }