如何获取我的环境的当前区域设置?
曾尝试在Linux中使用以下代码,但始终在不同的LANG
设置下返回“C”。
#include #include #include 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
我该怎么做才能在Linux中获得当前的语言环境设置(比如Ubuntu)?
另一个问题是,在Windows中获取区域设置是否相同?
来自man 3 setlocale
(新格言:“如果有疑问,请阅读整个联机帮助页。”):
如果locale为
""
,则应根据环境变量设置应修改的语言环境的每个部分。
因此,我们可以通过在程序开头调用setlocale
来读取环境变量,如下所示:
#include #include 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; }
我的系统不支持zh_CN
语言环境,因为以下输出显示:
$ ./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:我不知道Windows语言环境。 我建议从MSDN搜索开始 ,然后打开一个单独的 Stack Overflow问题,如果你还有问题的话。
刚想出如何通过C ++获取语言环境,只需使用空字符串“”来构造std :: locale,它与setlocale(LC_ALL,“”)的作用相同。
locale l(""); cout<<"Locale by C++: "<
此链接描述了C语言环境和C ++语言环境之间的细节差异。
考虑代替std :: locale的一个很好的替代方法是boost :: locale,它能够返回更可靠的信息 – 请参阅http://www.boost.org/doc/libs/1_52_0/libs/locale/doc/html/ locale_information.html
boost :: locale :: info具有以下成员函数:
std::string name() -- the full name of the locale, for example en_US.UTF-8 std::string language() -- the ISO-639 language code of the current locale, for example "en". std::string country() -- the ISO-3199 country code of the current locale, for example "US". std::string variant() -- the variant of current locale, for example "euro". std::string encoding() -- the encoding used for char based strings, for example "UTF-8" bool utf8() -- a fast way to check whether the encoding is UTF-8.