C++ reset locale to "C" globally?
Asked Answered
S

1

15

In a project I am currently working on I link to a proprietary dynamic library. As soon as I run the library's initialize function, the behavior of logging and printing of numbers changes.

Commas have been inserted at every third decimal. i.e.

cout << 123456789 << endl

used to print out 123456789 and now it prints 123,456,789. This is horribly annoying, because this behavior is not what I want.

This issue is not only apparent in the binary I am compiling, but also shows up in all the couts and stringstreams in the libraries that I link to it.

I have tried using this line of code after calling the initialize function:

setlocale(LC_ALL,"C");

thinking it might reset my locale to the default but to no avail. The commas persist!

This snippet of code:

std::cout.imbue(std::locale("C"));

works to reset the locale of couts and every stringstream I apply it too. However, do I really need to call imbue on EVERY stringstream declared in EVERY library I link to? There are some libraries that are proprietary and I cannot actually change their source code.

There must be a way to reset the locale back to "C" globally?

Straightforward answered 19/6, 2013 at 23:8 Comment(0)
H
11

I believe std::locale::global(std::locale("C")); should do the trick. See http://en.cppreference.com/w/cpp/locale/locale/global

Note that this only affects streams created after this call.

Any streams such as cout that the other library already imbued would have to be re-imbued back to the desired default locale.

And finally I would strongly suggest filing a defect report against the library you're using because it's pretty unjustifiable to to unilaterally make such striking global changes within your initialization function.

Hausmann answered 19/6, 2013 at 23:14 Comment(3)
yes, but the OP must remember that locale::global (as indicated in the linked page) only affect the streams constructed after the call. So, cin, cout, cerr and other streams are not imbued with the global locale, one must do that manually;Howell
@Mark B, Thank you. That worked like a dream. @Massa, thanks for the insight. So I can assume that streams inherit the locale of whatever the global locale is at the moment of their declaration?Straightforward
they inherit the locale of the global locale is at the moment of their initialization (they can be declared as class members and initialized on constructors, etc. etc.)Howell

© 2022 - 2024 — McMap. All rights reserved.