C++ 標準ライブラリ <locale>
C++ 標準ライブラリでは、localeクラスは、プログラムのローカリゼーション動作、特に言語や文化に関連するフォーマット設定や変換操作を制御するメカニズムを提供します。localeこのクラスは#include <locale>ヘッダーファイル内で定義されています。
C++ 標準ライブラリのlocaleモジュールは、プログラムがユーザーのロケール設定に基づいてテキストデータ(数値、日付、時刻のフォーマット、文字列の比較や並べ替えなど)を処理する方法を提供します。これにより、国際化アプリケーションの作成がより容易になります。
構文
以下は使用するlocaleクラスの基本構文です:
#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;
}
例
1. 基本的な使用方法
以下は、使用方法を示す簡単な例です:locale数字をフォーマットする方法:
例
#include <iostream>
#include <locale>
int main() {
std::locale loc("en_US.UTF-8"); // アメリカ英語に設定
std::cout.imbue(loc); // cout の locale を設定
double number = 1234567.89;
std::cout << "Formatted number: " << number << std::endl;
return 0;
}
#include <locale>
int main() {
std::locale loc("en_US.UTF-8"); // アメリカ英語に設定
std::cout.imbue(loc); // cout の locale を設定
double number = 1234567.89;
std::cout << "Formatted number: " << number << std::endl;
return 0;
}
出力結果:
Formatted number: 1,234,567.89
2. 文字列の比較
を使用するとlocale特定のロケールの規則に従って文字列を比較できます:
例
#include <iostream>
#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;
}
#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;
}
出力結果:
apple comes before banana
3. 日付と時刻のフォーマット
locale日付と時刻のフォーマットにも使用できます:
例
#include <iostream>
#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;
}
#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;
}
出力結果(例):
Current date: Monday, March 14, 2023
localeこのクラスは、C++ 標準ライブラリの強力なツールであり、開発者がさまざまなロケール設定に対応するアプリケーションを作成できるようにします。