C 庫 - setlocale() 函式



C 庫的 setlocale() 函式設定或讀取與位置相關的 資訊。此函式在特定系統中安裝系統區域設定。為了修改剩餘的影響,它在下次呼叫 setlocale 之前執行所有 C STL 的敏感函式。

語法

以下是 C setlocale() 函式的語法:

char *setlocale(int category, const char *locale)

引數

以下是不同區域設定類別的列表:

  • category - 這是一個命名常量,指定受區域設定影響的函式類別。

    • LC_ALL 用於以下所有類別。

    • LC_COLLATE 用於字串比較。參見 strcoll()。
    • LC_CTYPE 用於字元分類和轉換。例如:strtoupper()。
    • LC_MONETARY 用於貨幣格式化,用於 localeconv()。
    • LC_NUMERIC 用於十進位制分隔符,用於 localeconv()。
    • LC_TIME 用於使用 strftime() 進行日期和時間格式化。
    • LC_MESSAGES 用於系統響應。
  • locale - 如果 locale 為 NULL 或空字串 (""),則區域設定名稱將從與上述類別名稱相同的環境變數的值中設定。

返回值

setlocale() 函式呼叫成功則返回一個與已設定區域設定對應的、不透明的字串。如果請求無法滿足,則返回值為 NULL。

示例 1

以下是一個基本的 C 程式,用於演示 setlocale() 函式的用法。

#include <locale.h>
#include <stdio.h>
#include <time.h>

int main () {
   time_t currtime;
   struct tm *timer;
   char buffer[80];

   time( &currtime );
   timer = localtime( &currtime );

   printf("Locale is: %s\n", setlocale(LC_ALL, "en_GB"));
   strftime(buffer,80,"%c", timer );
   printf("Date is: %s\n", buffer);

  
   printf("Locale is: %s\n", setlocale(LC_ALL, "de_DE"));
   strftime(buffer,80,"%c", timer );
   printf("Date is: %s\n", buffer);

   return(0);
}

輸出

執行程式碼後,我們將得到以下結果:

Locale is: en_GB                                                            
Date is: Fri 05 Dec 2014 10:35:02 UTC                                       
Locale is: de_DE                                                            
Date is: Fr 05 Dez 2014 10:35:02 UTC

示例 2

在此示例中,我們透過使用 setlocale() 函式來說明使用 LC_Numeric 區域設定的十進位制分隔符。

#include <stdio.h>
#include <locale.h>

int main() {
   // Set the locale to the user's default locale
   setlocale(LC_NUMERIC, "");

   // Get the current locale for LC_NUMERIC
   char *currentLocale = setlocale(LC_NUMERIC, NULL);
   printf("Current LC_NUMERIC locale: %s\n", currentLocale);

   // Display the floating-point number with the current locale
   double number = 65743.6789;
   printf("Formatted number: %.2f\n", number);

   return 0;
}

輸出

執行上述程式碼後,我們將得到以下結果:

Current LC_NUMERIC locale: en_US.UTF-8
Formatted number: 65743.68

示例 3

在此示例中,我們使用 setlocale() 函式來設定 LC_TIME(本地化),以顯示日期和時間格式。

#include <stdio.h>
#include <time.h>
#include <locale.h>

int main() {
    // Set the locale to the user's default locale
    setlocale(LC_TIME, "");

    // Get the current locale for LC_TIME
    char *currentLocale = setlocale(LC_TIME, NULL);
    printf("Current LC_TIME locale: %s\n", currentLocale);

    // Display the current date and time
    time_t currentTime;
    struct tm *timeInfo;

    time(&currentTime);
    timeInfo = localtime(&currentTime);

    char formattedTime[100];
    strftime(formattedTime, sizeof(formattedTime), "%c", timeInfo);
    printf("Formatted date and time: %s\n", formattedTime);

    return 0;
}

輸出

上述程式碼產生以下結果:

Current LC_TIME locale: en_US.UTF-8
Formatted date and time: Mon 20 May 2024 05:48:37 AM UTC
廣告
© . All rights reserved.