【问题标题】:setLocale for reading float numbers from stringsetLocale 从字符串中读取浮点数
【发布时间】:2015-09-23 10:55:42
【问题描述】:

我在 Ubuntu 上工作并使用英文键盘。当我想使用“strtof”函数从 cpp 中的字符串解析浮点数时,它假设逗号,而不是点作为浮点数。作为一个已知的解决方案,我尝试使用 setlocale(LC_NUMERIC, "C") 但这仅在调用 strtof 的同一函数范围内有帮助。但是,如果我需要将 setlocale 添加到每个函数范围,则需要花费太多时间。我试图在 main 函数中这样做,不幸的是只修复了 main 范围内的问题。

如何让它在全球范围内运作?

【问题讨论】:

  • 默认情况下,程序启动时语言环境应设置为“C”。如果不是,你应该检查它在哪里设置为不同的东西。

标签: c++ ubuntu setlocale


【解决方案1】:

您可以设置全局语言环境:

std::locale::global(std::locale("C"));//default.

这应该会影响所有依赖全局语言环境的函数。

请注意,cout(我认为是 cin 和 cerr)在创建时就包含了全局语言环境。即使您的代码的第一行设置了全局语言环境,流也可能是之前创建的,因此您必须为流注入新的语言环境。

如果您在其他地方需要特定于区域设置的行为,但不希望默认情况下您的数字格式被弄乱,boost::locale 解决了这个问题 -- 你可以看到这个问题:What are the tradeoffs between boost::locale and std::locale?

这是一个输出示例,但解析行为是相同的:

auto demo = [](const std::string& label)
{
    float f = 1234.567890;
    std::cout << label << "\n";
    std::cout << "\t streamed:  " << f << "\n";
    std::cout << "\t to_string: " << std::to_string(f) << "\n";
};

std::locale::global(std::locale("C"));//default.
std::cout.imbue(std::locale()); // imbue cout with the global locale.
demo("c locale");

std::locale::global(std::locale("de_DE"));//default.
std::cout.imbue(std::locale()); // imbue cout with the global locale.
demo("std de locale");

boost::locale::generator gen;
std::locale::global(gen("de_DE.UTF-8"));
std::cout.imbue(std::locale()); // imbue cout with the global locale.
demo("boost de locale");

提供以下结果:

c locale
     streamed:  1234.57
     to_string: 1234.567871
std de locale
     streamed:  1.234,57
     to_string: 1234,567871
boost de locale
     streamed:  1234.57
     to_string: 1234,567871

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多