Ensuring your C++ program works correctly with different locales and languages involves several considerations. Here's a guide on best practices for localization in C++:
<locale>
LibraryC++ provides the <locale>
library for handling localization. Start by setting the global locale:
#include <iostream>
#include <locale>
int main() {
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
std::cout << "Current locale: "
<< std::locale().name() << '\n';
}
Current locale: C
For better support of non-ASCII characters, use wide character types like wchar_t
:
#include <iostream>
#include <string>
#include <locale>
int main() {
std::locale::global(std::locale(""));
std::wcout.imbue(std::locale());
std::wstring greeting = L"Hello, world!";
std::wcout << greeting << L'\n';
}
Hello, world!
Different locales use different number formats. Use std::numpunct
to handle this:
#include <iostream>
#include <locale>
#include <iomanip>
int main() {
std::locale::global(std::locale("de_DE.UTF-8"));
std::cout.imbue(std::locale());
double number = 1234567.89;
std::cout << std::fixed << std::setprecision(2)
<< number;
}
1.234.567,89
Use std::time_put
for locale-aware date and time formatting:
#include <iostream>
#include <locale>
#include <ctime>
#include <iomanip>
int main() {
std::time_t t = std::time(nullptr);
#ifdef _WIN32
std::locale::global(std::locale(
"French_France.1252"));
std::cout.imbue(std::locale());
std::tm now;
localtime_s(&now, &t);
std::cout << std::put_time(&now, "%A %d %B %Y");
#else
std::locale::global(std::locale(
"fr_FR.UTF-8"));
std::cout.imbue(std::locale());
std::tm* now = std::localtime(&t);
std::cout << std::put_time(now, "%A %d %B %Y");
#endif
}
jeudi 28 juin 2024
For larger applications, consider using message catalogs. While C++ doesn't have built-in support for this, you can use libraries like GNU gettext:
#include <libintl.h>
#include <locale.h>
#include <iostream>
#define _(string) gettext(string)
int main() {
setlocale(LC_ALL, "");
bindtextdomain("myapp", "/path/to/locale");
textdomain("myapp");
std::cout << _("Hello, world!") << '\n';
}
Remember to compile your message catalogs and place them in the correct directory structure.
Always test your application with various locales and input data. Be particularly careful with:
By following these practices, you can create C++ programs that work well across different locales and languages. Remember that localization is an ongoing process, and you may need to update your application as new locales or language requirements arise.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to C++ character types, the Unicode standard, character encoding, and C-style strings