如何获取我的环境的当前区域设置

How to get current locale of my environment?

本文关键字:区域 设置 环境 我的 何获取 获取      更新时间:2023-10-16

曾在Linux中尝试过以下代码,但在不同的LANG设置下总是返回"C"。

#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

我应该怎么做才能在Linux(比如Ubuntu)中获得当前的区域设置?

另一个问题是,在Windows中获取区域设置的方式是否相同?

来自man 3 setlocale(新格言:"如果有疑问,请阅读整个手册页。"):

如果区域设置为"",则应根据环境变量设置区域设置的每个部分。

因此,我们可以通过在程序开始时调用setlocale来读取环境变量,如下所示:

#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;
}

我的系统不支持zh_CN区域设置,如下输出所示:

$/a.outLC_ALL:en_US.utf8LC_CTYPE:en_US.utf8$export LANG=zh_CN.UTF-8$/a.outLC_ALL:CLC_CTYPE:C

Windows:我对Windows区域设置一无所知。我建议从MSDN搜索开始,如果您还有问题,请打开单独的堆栈溢出问题。

刚刚学会了如何通过C++获得语言环境,只需使用一个空字符串"来构造std::locale,它与setlocale(LC_ALL,")做同样的事情。

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

此链接描述了C语言环境和C++语言环境之间的细节差异。

对于Windows,请使用以下代码:

LCID lcid = GetThreadLocale();
wchar_t name[LOCALE_NAME_MAX_LENGTH];
if (LCIDToLocaleName(lcid, name, LOCALE_NAME_MAX_LENGTH, 0) == 0)
    error(GetLastError());
std::wcout << L"Locale name = " << name << std::endl;

这将打印类似于"en-US"的内容。

要清除子语言信息,请使用以下方法:

wchar_t parentLocateName[LOCALE_NAME_MAX_LENGTH];
if (GetLocaleInfoEx(name, LOCALE_SPARENT, parentLocateName, LOCALE_NAME_MAX_LENGTH) == 0)
    error(GetLastError());
std::wcout << L"parentLocateName = " << parentLocateName << std::endl;

这只会给你一个"en"。

一个很好的替代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.

std::locale的默认构造函数创建全局C++区域设置的副本。

因此,要获得当前区域设置的名称:

std::cout << std::locale().name() << 'n';