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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With