Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Set Locale across the entire program

Tags:

c++

global

locale

I"m looking for a way to set the locale across the entire program, if that"s even possible.

I set the locale in my main function like this:

int main()
{
    setlocale(LC_ALL, "");
    ....
    return 0;
}

However, it doesn"t set the locale to my different classes/methods across the entire program. I"d rather not write this line on top of every method that will print on the screen and creating a C++ locale object and passing it around doesn"t quite feel acceptable.

Thank you for your time.

like image 989
Tristan Avatar asked Sep 06 '14 03:09

Tristan


2 Answers

The two functions that modify global locale settings are std::setlocale and std::locale::global. All future C and C++ I/O and string manipulation will use them, except for the six standard I/O C++ streams, which are constructed before your code runs, so you may have to imbue them individually if so desired:

#include <locale>
#include <clocale>
int main()
{
   std::setlocale(LC_ALL, ""); // for C and C++ where synced with stdio
   std::locale::global(std::locale("")); // for C++
   std::cout.imbue(std::locale());
   // cerr, clog, wcout, wcerr, wclog as needed
like image 186
Cubbi Avatar answered Nov 14 '22 07:11

Cubbi


setlocale used for setting the locale, but its scope if decided by the first parameter (i.e. flag) that we pass. In your case, "LC_ALL".

There are two ways to set the locale. So, as per behavior of the setlocale, if you pass second parameter as "" or NULL, it takes the default from the system enviornment (LANG). Code for reference as below:

setenv("LANG","en_US.utf8",1);
cout << "GET ENV .... " << getenv("LANG");
setlocale(LC_ALL,"");

The other way is to use the locale, as below:

setlocale(LC_ALL,"en_US.utf8");

Code Illustration

like image 21
parasrish Avatar answered Nov 14 '22 08:11

parasrish