-1

I work on Ubuntu and use an english keyboard.When I want to parse float from string in cpp using "strtof" function it is assuming commas, instead of dots as floating point. As a known solution I tried to use setlocale(LC_NUMERIC, "C") however this only helps within the same function scope where strtof is called. However If I need to add setlocale to every function scope it would take too much time. I tried to do this in main function, unfortunately only fixed the problem in the scope of main.

How to make it globally working?

in4001
  • 656
  • 6
  • 24
  • The locale should be set to "C" at program startup by default. If it isn't you should check where else it is set to something different. – Simon Kraemer Sep 23 '15 at 11:00

1 Answers1

1

You can set the global locale:

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

Which should affect all functions which rely on the global locale.

Note that cout (and I presume cin and cerr) are imbued with the global locale at the moment they are created. Even if the first line of your code sets the global locale, the streams may have been created earlier, so you must imbue the stream with the new locale.

If you need locale specific behavior elsewhere, but don't want your number formatting messed with by default, boost::locale solved this issue -- you can see this question:What are the tradeoffs between boost::locale and std::locale?

Here's an example of output, but parsing behavior is identical:

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");

Which provides the following result:

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
Community
  • 1
  • 1
Spacemoose
  • 3,856
  • 1
  • 27
  • 48