问题描述
向C ++程序添加多语言支持的最佳方法是什么?
what's the best way to add multilanguage support to a C++ program?
如果可能,应该从纯文本文件中读取该语言,该文件包含类似键/值对(§WelcomeMessage§"Hello%s!")的内容.
If possible, the language should be read in from a plain text file containing something like key-value pairs (§WelcomeMessage§ "Hello %s!").
我想到了类似添加一个localizedString(key)函数的操作,该函数返回加载的语言文件的字符串.有更好或更有效的方法吗?
I thought of something like adding a localizedString(key) function that returns the string of the loaded language file. Are there better or more efficient ways?
//half-pseudo code
//somewhere load the language key value pairs into langfile[]
string localizedString(key)
{
//do something else here with the string like parsing placeholders
return langfile[key];
}
cout << localizedString(§WelcomeMessage§);
推荐答案
没有外部库的最简单方法:
Simplest way without external libraries:
//strings.h
// strings.h
enum
{
LANG_EN_EN,
LANG_EN_AU
};
enum
{
STRING_HELLO,
STRING_DO_SOMETHING,
STRING_GOODBYE
};
//strings.c
// strings.c
char* en_gb[] = {"Well, Hello","Please do something","Goodbye"};
char* en_au[] = {"Morning, Cobber","do somin'","See Ya"};
char** languages[MAX_LANGUAGES] = {en_gb,en_au};
这将为您提供所需的内容.显然,您可以从文件中读取字符串.即
This will give you what you want. Obviously you could read the strings from a file. I.e.
//en_au.lang
// en_au.lang
STRING_HELLO,"Morning, CObber"
STRING_DO_SOMETHING,"do somin'"
STRING_GOODBYE,"See Ya"
但是您需要一个字符串名称列表以与字符串标题匹配.即
But you would need a list of string names to match to the string titles. i.e.
//parse_strings.c
// parse_strings.c
struct PARSE_STRINGS
{
char* string_name;
int string_id;
}
PARSE_STRINGS[] = {{"STRING_HELLO",STRING_HELLO},
{"STRING_DO_SOMETHING",STRING_DO_SOMETHING},
{"STRING_GOODBYE",STRING_GOODBYE}};
在C ++中,上面的代码应该稍微容易一些,因为您可以使用枚举类的toString()方法(或者使用它,无论如何-都可以查找它).
The above should be slightly easier in C++ as you could use the enum classes toString() method (or what ever it as - can't be bothered to look it up).
您要做的就是解析语言文件.
All you then have to do is parse the language files.
我希望这会有所帮助.
PS:并访问字符串:
PS: and to access the strings:
languages[current_language][STRING_HELLO]
PPS:对C ++ C答案的一半表示歉意.
PPS: apologies for the half c half C++ answer.
这篇关于C ++,多语言/本地化支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!