I18n C ++ hello world with plurals

时间:2009-07-10 07:32:07

标签: c++ internationalization gettext

Complete C++ i18n gettext() “hello world” example具有适用于简单固定字符串的C ++代码。我现在正在寻找一个与复数一起使用的示例程序。此示例代码显示六行。英语中只有一个是正确的。它没有正确处理复数。

cat >helloplurals.cxx <<EOF
// hellopurals.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
#include <stdio.h>
int main (){
    setlocale(LC_ALL, "");
    bindtextdomain("helloplurals", ".");
    textdomain( "helloplurals");
    for (int ii=0; ii<5; ii++)
        printf (gettext("Hello world with %d moon.\n"), ii);
}
EOF
g++ -o helloplurals helloplurals.cxx
./helloplurals

GNU gettext() for plural forms描述了语言处理复数的各种方式,例如:

  • 韩国人 - 没有祸害
  • 英语 - 两种形式,单数仅用于一种
  • 法语 - 两种形式,单数用于零和一个
  • 波兰语 - 三种形式,一种特殊情况和一些以2,3或4结尾的数字

我的期望是代码能够专门针对所有上述情况工作(给定消息目录)以及此处未列出的其他几种变体。用英语执行时的正确输出是:

Hello world with 0 moons.
Hello world with 1 moon.
Hello world with 2 moons.
Hello world with 3 moons.
Hello world with 4 moons.

3 个答案:

答案 0 :(得分:3)

我不确定你想要什么。如果您的示例略微修改了您想要的输出,只需用

替换printf行
printf(ngettext("Hello world with %d moon\n", "Hello world with %d moons\n", ii), ii);

但由于这是对unwind答案的一个微不足道的修改,而gettext文档有非常相似的例子,

printf (ngettext ("%d file removed", "%d files removed", n), n);

我想知道它是否真的是你想要的。如果你想使用带有更多C ++语法的gettext,你将不得不寻找像Boost :: Format这样的库。

答案 1 :(得分:2)

首先,gettext()并不神奇。它不会以某种方式包含所有语言中所有单词的全球字典。

所有这一切都是在你的应用程序的消息数据库中查找消息的翻译,所以这个例子假设有这样一个文件(gettext()可以找到它,这可能有些棘手)。

接下来,你错了。您链接到的页面描述了ngettext()功能,这是您必须使用的功能,以便获得随计数而变化的翻译。

你的电话应该是这样的:

printf("%s", ngettext("moon", "moons", ii));

这使gettext可以根据count参数决定使用哪种表单。

答案 2 :(得分:0)

您是否真的为不同的复数形式制作.po文件?请参阅description of the gettext workflow on Wikipedia。另请阅读gettxt documentation about plural forms所有,特别是包含复数形式的.po文件示例。