我在 macOS 10.14.6 系統上使用來自 cppreference.com的示例程式setlocale(),但是,輸出未本地化。我檢查了setlocale()is not的回傳值,NULL并嘗試了各種語言環境規范以嘗試獲取十進制逗號,例如de, de_DE, de_DE.utf8。
為什么這不起作用?
如何找出輸出不受影響的原因,以及是否是因為不正確的語言環境名稱?
在同一作業系統上,Python 的語言環境更改似乎確實有效(因為它們會影響在同一行程中運行的 C 代碼的數字列印)。因此,我認為問題不在于不支持此語言環境。
完整程式:
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
int main(void)
{
// the C locale will be UTF-8 enabled English;
// decimal dot will be German
// date and time formatting will be Japanese
setlocale(LC_ALL, "en_US.UTF-8");
setlocale(LC_NUMERIC, "de_DE.utf8");
setlocale(LC_TIME, "ja_JP.utf8");
wchar_t str[100];
time_t t = time(NULL);
wcsftime(str, 100, L"%A %c", localtime(&t));
wprintf(L"Number: %.2f\nDate: %ls\n", 3.14, str);
}
uj5u.com熱心網友回復:
從終端,locale -a可用于查看所有可用的語言環境。
在我的系統1上,locale -a | grep de_產生以下結果
de_CH
de_DE.UTF-8
de_AT.ISO8859-1
de_AT.UTF-8
de_AT.ISO8859-15
de_DE.ISO8859-15
de_CH.UTF-8
de_DE-A.ISO8859-1
de_CH.ISO8859-15
de_DE.ISO8859-1
de_CH.ISO8859-1
de_AT
de_DE
setlocaleNULL在引陣列合沒有意義的情況下回傳。在我的系統1上,
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
int main(void)
{
// the C locale will be UTF-8 enabled English;
// decimal dot will be German
// date and time formatting will be Japanese
char *all = setlocale(LC_ALL, "en_US.UTF-8");
char *num = setlocale(LC_NUMERIC, "de_DE.utf8");
char *tim = setlocale(LC_TIME, "ja_JP.utf8");
printf("%s\n%s\n%s\n", all, num, tim);
wchar_t str[100];
time_t t = time(NULL);
wcsftime(str, 100, L"%A %c", localtime(&t));
wprintf(L"Number: %.2f\nDate: %ls\n", 3.14, str);
}
輸出
en_US.UTF-8
(null)
(null)
Number: 3.14
Date: Thursday Thu May 12 08:35:37 2022
使用先前串列中的語言環境
#include <stdio.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
int main(void)
{
// the C locale will be UTF-8 enabled English;
// decimal dot will be German
// date and time formatting will be Japanese
char *all = setlocale(LC_ALL, "en_US.UTF-8");
char *num = setlocale(LC_NUMERIC, "de_DE.UTF-8");
char *tim = setlocale(LC_TIME, "ja_JP.UTF-8");
printf("%s\n%s\n%s\n", all, num, tim);
wchar_t str[100];
time_t t = time(NULL);
wcsftime(str, 100, L"%A %c", localtime(&t));
wprintf(L"Number: %.2f\nDate: %ls\n", 3.14, str);
}
輸出
en_US.UTF-8
de_DE.UTF-8
ja_JP.UTF-8
Number: 3,14
Date: 木曜日 木 5/12 08:37:51 2022
1請注意,這是在 macOS 10.15.7 上測驗的。macOS 10.14.6 上的結果可能有所不同。你不應該盲目相信你找到的例子,包括我在這里,而是檢查你自己系統的語言環境。
locale自 Mac OS X 10.4 起已可用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/473147.html
