Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current locale of my environment?

Tags:

c++

c

locale

Had tried following code in Linux, but always return 'C' under different LANG settings.

#include <iostream> #include <locale.h> #include <locale> using namespace std;  int main() {     cout<<"locale 1: "<<setlocale(LC_ALL, NULL)<<endl;     cout<<"locale 2: "<<setlocale(LC_CTYPE, NULL)<<endl;      locale l;     cout<<"locale 3: "<<l.name()<<endl; }  $ ./a.out locale 1: C locale 2: C locale 3: C $ $ export LANG=zh_CN.UTF-8 $ ./a.out locale 1: C locale 2: C locale 3: C 

What should I do to get current locale setting in Linux(like Ubuntu)?

Another question is, is it the same way to get locale in Windows?

like image 781
Deqing Avatar asked Aug 29 '12 03:08

Deqing


2 Answers

From man 3 setlocale (New maxim: "When in doubt, read the entire manpage."):

If locale is "", each part of the locale that should be modified is set according to the environment variables.

So, we can read the environment variables by calling setlocale at the beginning of the program, as follows:

#include <iostream> #include <locale.h> using namespace std;  int main() {     setlocale(LC_ALL, "");     cout << "LC_ALL: " << setlocale(LC_ALL, NULL) << endl;     cout << "LC_CTYPE: " << setlocale(LC_CTYPE, NULL) << endl;     return 0; } 

My system does not support the zh_CN locale, as the following output reveals:

 $ ./a.out  LC_ALL: en_US.utf8 LC_CTYPE: en_US.utf8 $ export LANG=zh_CN.UTF-8 $ ./a.out  LC_ALL: C LC_CTYPE: C 

Windows: I have no idea about Windows locales. I suggest starting with an MSDN search, and then opening a separate Stack Overflow question if you still have questions.

like image 58
Dietrich Epp Avatar answered Sep 20 '22 23:09

Dietrich Epp


Just figured out how to get locale by C++, simply use an empty string "" to construct std::locale, which does the same thing as setlocale(LC_ALL, "").

locale l(""); cout<<"Locale by C++: "<<l.name()<<endl; 

This link described differences in details between C locale and C++ locale.

like image 26
Deqing Avatar answered Sep 19 '22 23:09

Deqing