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

3

9

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.

Hypha answered 29/3, 2012 at 20:36 Comment(3)
Haven't used it, but is this what you're after? en.cppreference.com/w/cpp/io/ios_base/getloc edit: never mind, I found the return value is the current locale. See Corbin's answer.Delarosa
Do you want the global locale (defaulting to "C"), or the environment's locale?Appraisal
I want the value of whatever someone set before using std::locale::global.Hypha
P
16

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

Proximal answered 29/3, 2012 at 20:39 Comment(0)
H
5

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

Halona answered 29/3, 2012 at 20:39 Comment(0)
P
2

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.

Postal answered 29/3, 2012 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.