std::setlocale
定义于头文件 <clocale> |
||
char* setlocale( int category, const char* locale ); |
||
setlocale
函数安装指定的系统区域设置或其部分作为新的 C 区域设置。这些修改持续有效,并影响所有区域设置敏感的 C 库函数的执行,直到下次调用 setlocale
。如果 locale
是一个空指针,setlocale
查询当前的 C 区域设置而不修改它。
目录 |
[编辑] 参数
category | - | 区域设置类别标识符,LC_xxx 宏之一。可以是 0。 |
locale | - | 系统特定的区域设置标识符。可以是 "" 表示用户首选的区域设置,或者 "C" 表示最小的区域设置 |
[编辑] 返回值
指向一个窄的空终止字符串的指针,该字符串标识应用更改(如果有)后的 C 区域设置;如果失败,则为空指针。
返回字符串的副本以及在此 std::setlocale
调用中使用的类别,可以在程序稍后使用,以将区域设置恢复到此调用结束时的状态。
[编辑] 注释
在程序启动期间,在任何用户代码运行之前,会执行等效于 std::setlocale(LC_ALL, "C"); 的操作。
尽管返回类型是 char*,但修改指向的字符是未定义的行为。
由于 setlocale
修改了影响区域设置相关函数执行的全局状态,因此从一个线程调用它是未定义的行为,而另一个线程正在执行以下任何函数:std::fprintf, std::isprint, std::iswdigit, std::localeconv, std::tolower, std::fscanf, std::ispunct, std::iswgraph, std::mblen, std::toupper, std::isalnum, std::isspace, std::iswlower, std::mbstowcs, std::towlower, std::isalpha, std::isupper, std::iswprint, std::mbtowc, std::towupper, std::isblank, std::iswalnum, std::iswpunct, std::setlocale
, std::wcscoll, std::iscntrl, std::iswalpha, std::iswspace, std::strcoll, std::wcstod, std::isdigit, std::iswblank, std::iswupper, std::strerror, std::wcstombs, std::isgraph, std::iswcntrl, std::iswxdigit, std::strtod, std::wcsxfrm, std::islower, std::iswctype, std::isxdigit。
POSIX 还定义了一个名为 "POSIX" 的区域设置,它始终可访问,并且与默认的最小 "C" 区域设置完全等效。
POSIX 还规定,后续对 setlocale
的调用可能会使返回的指针(而不仅仅是指向字符串的内容)失效。
[编辑] 示例
#include <clocale> #include <cstdio> #include <ctime> #include <cwchar> #include <iterator> #include <string> int main() { // Make a "deep copy" of current locale name. std::string prev_loc = std::setlocale(LC_ALL, nullptr); // The C locale will be UTF-8 enabled English, // decimal dot will be German, // date and time formatting will be Japanese. if (const char* loc = std::setlocale(LC_ALL, "en_US.UTF-8")) std::wprintf(L"New LC_ALL locale: %s\n", loc); if (const char* loc = std::setlocale(LC_NUMERIC, "de_DE.UTF-8")) std::wprintf(L"New LC_NUMERIC locale: %s\n", loc); if (const char* loc = std::setlocale(LC_TIME, "ja_JP.UTF-8")) std::wprintf(L"New LC_TIME locale: %s\n", loc); wchar_t buf[100]; std::time_t t = std::time(nullptr); std::wcsftime(buf, std::size(buf), L"%A %c", std::localtime(&t)); std::wprintf(L"Number: %.2f\nDate: %Ls\n", 3.14, buf); // Restore the previous locale. if (const char* loc = std::setlocale(LC_ALL, prev_loc.c_str())) std::wprintf(L"Restorred LC_ALL locale: %s\n", loc); }
可能的输出
New LC_ALL locale: en_US.UTF-8 New LC_NUMERIC locale: de_DE.UTF-8 New LC_TIME locale: ja_JP.UTF-8 Number: 3,14 Date: 日曜日 2022年11月06日 20時40分59秒 Restorred LC_ALL locale: C
[编辑] 参见
std::setlocale 的区域设置类别 (宏常量) | |
封装文化差异的多态 facets 集合 (类) | |
setlocale 的 C 文档
|
[编辑] 外部链接
1. | Windows 区域设置名称列表. |
2. | Linux 区域设置名称列表. |