名稱空間
變體
操作

std::setlocale

來自 cppreference.com
< cpp‎ | locale
 
 
 
 
定義於標頭檔案 <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::fprintfstd::isprintstd::iswdigitstd::localeconvstd::tolowerstd::fscanfstd::ispunctstd::iswgraphstd::mblenstd::toupperstd::isalnumstd::isspacestd::iswlowerstd::mbstowcsstd::towlowerstd::isalphastd::isupperstd::iswprintstd::mbtowcstd::towupperstd::isblankstd::iswalnumstd::iswpunctstd::setlocalestd::wcscollstd::iscntrlstd::iswalphastd::iswspacestd::strcollstd::wcstodstd::isdigitstd::iswblankstd::iswupperstd::strerrorstd::wcstombsstd::isgraphstd::iswcntrlstd::iswxdigitstd::strtodstd::wcsxfrmstd::islowerstd::iswctypestd::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 的區域設定類別
(宏常量) [編輯]
封裝文化差異的多型刻面集
(類) [編輯]
C 文件,關於 setlocale

[編輯] 外部連結

1.  Windows 區域設定名稱列表.
2.  Linux 區域設定名稱列表.