C++ Standard Library <locale>
In the C++ standard library,localeclasses provide a mechanism to control the localized behavior of a program, particularly formatting and conversion operations related to language and culture.localeClass in#include <locale>Defined in the header file.
In the C++ standard library,localeThe module provides a way for programs to process text data according to the user's locale, such as formatting numbers, dates, and times, as well as comparing and sorting strings. This makes it easier to write internationalized applications.
Syntax
The following is usinglocaleBasic syntax of classes:
#include <iostream>
#include <locale>
int main() {
// 创建一个默认的 locale 对象
std::locale loc;
// 使用 locale 对象
std::cout.imbue(loc); // 设置 cout 的 locale
// 显示当前 locale 的名称
std::cout << "Current locale: " << loc.name() << std::endl;
// 更多操作...
return 0;
}
Example
1. Basic usage
The following is a simple example showing how to uselocaleTo format numbers:
Example
#include <locale>
int main() {
std::locale loc("en_US.UTF-8"); // Set to American English
std::cout.imbue(loc); // Set the locale of cout
double number = 1234567.89;
std::cout << "Formatted number: " << number << std::endl;
return 0;
}
Output result:
Formatted number: 1,234,567.89
2. Compare strings
UsagelocaleStrings can be compared according to the rules of a specific locale:
Example
#include <locale>
#include <string>
int main() {
std::locale loc("en_US.UTF-8");
std::string str1 = "apple";
std::string str2 = "banana";
if (std::use_facet<std::collate<char>>(loc).compare(str1.c_str(), str1.c_str() + str1.size(),
str2.c_str(), str2.c_str() + str2.size()) < 0) {
std::cout << str1 << " comes before " << str2 << std::endl;
} else {
std::cout << str1 << " comes after " << str2 << std::endl;
}
return 0;
}
Output result:
apple comes before banana
3. Date and time formatting
localecan also be used to format dates and times:
Example
#include <locale>
#include <ctime>
int main() {
std::locale loc("en_US.UTF-8");
std::cout.imbue(loc);
std::time_t now = std::time(nullptr);
std::tm* timeinfo = std::localtime(&now);
char buffer[100];
std::strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", timeinfo);
std::cout << "Current date: " << buffer << std::endl;
return 0;
}
Output result(Example):
Current date: Monday, March 14, 2023
localeThe class is a powerful tool in the C++ standard library, allowing developers to write applications that can adapt to different locales.