真正的位置字符串格式

时间:2011-05-17 20:44:38

标签: c++ string formatting string-formatting boost-format

(注意:我知道Boost.Format,我正在寻找更好的方法来执行以下操作。)
首先是一个用例示例:在某些国家/地区,您通过首先调用他/她的姓氏和最后一个姓氏来命名一个人,而在其他国家/地区则恰恰相反。

现在,对于我的代码,我目前使用Boost.Format以下列方式解决这个问题:

#include <boost/format.hpp>
#include <iostream>
#include <stdlib.h>
#include <utility>

int main(){
    using namespace boost;

    int pos1 = 2, pos2 = 1;
    char const* surname = "Surname", *forename = "Forename";

    // decision on ordering here
    bool some_condition = false;

    if(some_condition)
      std::swap(pos1,pos2);

    char buf[64];
    sprintf(buf,"Hello %c%d%c %c%d%c",'%',pos1,'%','%',pos2,'%');
    // buf == "Hello %[pos1]% %[pos2]%"; with [posN] = value of posN

    std::cout << format(buf) % surname % forename;
}

现在,我宁愿这样做,即format行中的所有内容:

std::cout << format("Hello %%1%% %%2%%") % pos1 % pos2 % surname % forename;

但遗憾的是,这不起作用,因为我得到了一个很好的解析异常。

是否有任何库可以进行真正的位置格式化?或者甚至是用我不知道的Boost.Format来实现这个目标的方法吗?

6 个答案:

答案 0 :(得分:1)

在我看来,BoostSpiritKarma是权威的现代输出格式库。

答案 1 :(得分:1)

这是Message FormattingBoost.Locale部分,类似于GNU gettext

在其中你会写:

cout << format(translate("Hello {1} {2}!")) % forename % surname << endl;

然后翻译人员会使用消息目录翻译字符串:

msgid "Hello {1} {2}!"
msgstr "こんにちは {2}-さん!"

答案 2 :(得分:0)

我只是交换插值的值

std::swap(surname, forename)

那将完成这项工作。如果您不想弄乱它们,请参考:

const std::string& param1(bSwapThem? forename : surname);
const std::string& param2(bSwapThem? surname  : forename);

KISS

答案 3 :(得分:0)

听起来应该在系统区域设置中,但它看起来不像目前支持。

简单的方法怎么样?

   if(some_condition)
      std::cout << surname << " " << forename;
   else
      std::cout << forename << " " << surname;

答案 4 :(得分:0)

我会用?:

char const* surname = "Surname", *forename = "Forename";
bool swapFlag = (some_condition) ? true : false;

std::cout << "Hello " << (swapFlag ? surname : forename) << " " << (!swapFlag ? surname : forename) << std::endl;

答案 5 :(得分:0)

您可以通过递归应用格式来执行此操作:

cout << format(str(format("%%%1%%% %%%2%%%") % pos1 % pos2)) % surname % forname;

但是,我建议改用GNU gettext之类的东西。