Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the global locale that is currently set in C++?

Tags:

c++

locale

In C++, I can set the current locale like this:

std::locale::global(std::locale(name))

But how can I get the current global locale?

In my code, I need to get the current locale, save it to a tmp var, set the global locale to something else, output something, then set it back to the previous locale.

like image 781
Frank Avatar asked Mar 29 '12 20:03

Frank


3 Answers

If you call the default constructor of std::locale, you get it.

std::locale the_global_locale; // <-- automatically correct to std::locale::global
                               //     or a copy of std::locale::classic

More info here: http://en.cppreference.com/w/cpp/locale/locale/locale

like image 153
ipc Avatar answered Oct 12 '22 13:10

ipc


Its return value is the old locale, so just use that.

locale l = locale::global(locale(name));
//do some stuff here
locale::global(l);

Edit: Potentially useful: http://en.cppreference.com/w/cpp/locale/locale/global

like image 40
Corbin Avatar answered Oct 12 '22 12:10

Corbin


As ipc says, the default constructor for std::locale gives you a copy of the current global locale, but why do you need to cache and then reset the global locale?

C++ routines that use a locale can typically use a C++ locale object you specify, so you don't have to mess with the global locale at all. Using locale objects should be preferred to using the C++ global locale.

like image 37
bames53 Avatar answered Oct 12 '22 14:10

bames53