How is the setlocale function used?

The setlocale function is used to define the localization settings of a program.

The grammar is as follows:

#include <locale.h>
char* setlocale(int category, const char* locale);

Instructions for parameters:

  1. Category: Classification of the localization environment to be set, it can be one of the following constants:

    LC_ALL: Set all categories.
    LC_COLLATE: Set rules for string comparison and sorting.
    LC_CTYPE: Set rules for character classification and conversion.
    LC_MONETARY: Set currency format and symbols.
    LC_NUMERIC: Set number format.
    LC_TIME: Set date and time format.

  2. The locale string to be set can be in one of the following formats:

    An empty string (“”): to use the default locale.
    The name of a specific locale, such as “en_US”, “zh_CN”, etc.
    “C”: to use the localization environment of the C language, meaning no localization processing will be done.

The return value is the localized environment string if the setting is successful, otherwise NULL is returned.

Example Usage:

#include <iostream>
#include <locale.h>
#include <ctime>

int main() {
    setlocale(LC_ALL, ""); // 使用默认的本地化环境
    
    time_t now = time(NULL);
    struct tm* timeinfo = localtime(&now);
    char buffer[80];
    
    strftime(buffer, sizeof(buffer), "%c", timeinfo);
    std::cout << "当前日期和时间:" << buffer << std::endl;
    
    return 0;
}

The example program above has the default localization environment set and uses the strftime function to format the current date and time into a string for printing.

bannerAds