跳轉到內容

C 程式設計/locale.h

來自 Wikibooks,開放世界中的開放書籍

在計算機領域,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
華夏公益教科書