跳轉到內容

C 程式設計/locale.h

來自華夏公益教科書,自由的教科書

在計算中,locale.h 是一個用於本地化的 C 程式語言標頭檔案。該標頭檔案提供兩個關鍵函式:localeconvsetlocale。前者提供對當前區域設定的訪問,而後者允許設定當前區域設定。該標頭檔案還定義了結構 lconv,該結構儲存有關給定區域設定的資訊,包括對數字和貨幣顯示的本地偏好。

#include <locale.h>

char *setlocale(int category, const char *locale);
struct lconv *localeconv(void);

setlocale() 函式

[編輯 | 編輯原始碼]

setlocale() 函式用於設定或查詢程式的當前區域設定。

如果 locale 不是 NULL,則程式的當前區域設定會根據引數進行修改。引數 category 確定程式的當前區域設定中哪些部分應該被修改。

如果 localeNULL,則只查詢當前區域設定,不進行修改。

localeconv() 函式

[編輯 | 編輯原始碼]

localeconv() 函式返回一個指向當前區域設定的 struct lconv 的指標。該結構在下面下一節中顯示,幷包含與區域設定類別 LC_NUMERICLC_MONETARY 相關聯的所有值。程式也可以使用函式 printf()strfmon(),它們的行為符合使用的實際區域設定。

lconv 結構

[編輯 | 編輯原始碼]

struct lconv 包含以下欄位

數字(非貨幣)資訊

[編輯 | 編輯原始碼]
char *decimal_point;

基數字符。

char *thousands_sep;

基數字符左側數字分組的分隔符。

char *grouping;

每個元素都是一組中的數字數量;索引越高的元素越靠左。值為 CHAR_MAX 的元素表示不再進行分組。值為 0 的元素表示所有更靠左的分組都使用前面的元素。

貨幣資訊

[編輯 | 編輯原始碼]
char *int_curr_symbol;

前三個字元是來自 ISO 4217 的貨幣符號。第四個字元是分隔符。第五個字元是 '\0'

char *currency_symbol;

本地貨幣符號。

char *mon_decimal_point;

與上面的 decimal_point 相同。

char *mon_thousands_sep;

與上面的 thousands_sep 相同。

char *mon_grouping;

與上面的 grouping 相同。

char *positive_sign;

正值的符號。

char *negative_sign;

負值的符號。

char  int_frac_digits;

國際小數位數。

char  frac_digits;

本地小數位數。

char  p_cs_precedes;

如果 currency_symbol 位於正值之前,則為 1,如果位於之後,則為 0

char  p_sep_by_space;

如果空格將 currency_symbol 與正值隔開,則為 1

char  n_cs_precedes;

如果 currency_symbol 位於負值之前,則為 1,如果位於之後,則為 0

char  n_sep_by_space;

如果空格將 currency_symbol 與負值隔開,則為 1

char  p_sign_posn;
char  n_sign_posn;

正負號位置

  • 0:括號包圍數量和 currency_symbol
  • 1:符號字串位於數量和 currency_symbol 之前。
  • 2:符號字串位於數量和 currency_symbol 之後。
  • 3:符號字串緊挨著 currency_symbol 之前。
  • 4:符號字串緊挨著 currency_symbol 之後。
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

int main(void)
{
    /* Locale is set to "C" before this. This call sets it
       to the "current locale" by reading environment variables: */
    setlocale(LC_ALL, "");

    const struct lconv * const currentlocale = localeconv();

    printf("In the current locale, the default currency symbol is: %s\n",
        currentlocale->currency_symbol);

    return EXIT_SUCCESS;
}

參考資料

[編輯 | 編輯原始碼]
  1. locale.h by OpenGroup
  2. localeconv by OpenGroup
  3. setlocale by OpenGroup
華夏公益教科書