实际位置字符串格式
Real positional string formatting?
(注意:我知道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实现这一目标的方法?
在我看来,Boost.Spirit.Karma是权威的现代输出格式库。
这是 Boost.Locale 的消息格式化部分,类似于 GNU gettext。
你会在其中写:
cout << format(translate("Hello {1} {2}!")) % forename % surname << endl;
然后翻译器将使用消息目录翻译字符串:
msgid "Hello {1} {2}!"
msgstr "こんにちは {2}-さん!"
我只是交换你插值的值
std::swap(surname, forename)
这样就可以完成了这项工作。如果你不想惹他们,有参考:
const std::string& param1(bSwapThem? forename : surname);
const std::string& param2(bSwapThem? surname : forename);
吻
听起来应该在系统区域设置中,但看起来目前不受支持。
简单的方法呢?
if(some_condition)
std::cout << surname << " " << forename;
else
std::cout << forename << " " << surname;
我会用?:
char const* surname = "Surname", *forename = "Forename";
bool swapFlag = (some_condition) ? true : false;
std::cout << "Hello " << (swapFlag ? surname : forename) << " " << (!swapFlag ? surname : forename) << std::endl;
您可以通过递归应用格式来执行此操作:
cout << format(str(format("%%%1%%% %%%2%%%") % pos1 % pos2)) % surname % forname;
但是,我建议使用像GNU gettext这样的东西。
相关文章:
- 是否可以从格式字符串中检索"width"
- 我应该如何从 stdin C++ 中读取可变长度的格式字符串?
- 从用户定义的类生成格式字符串?
- 如何连接格式字符串?
- 如何在C++中将"%Y%m%d"格式字符串转换为time_t变量?
- CPPCHECK C++成员函数上的格式字符串
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- '|' scanf 格式字符串是什么意思
- 如何使用 msgfmt 验证格式字符串中的位置表示法占位符
- sscanf_s:格式字符串"%d"需要类型为"int *"的参数,但可变参数 4 的类型为"WORD *"
- C4477: 'fprintf' :格式字符串 '%s' 需要类型为"char *"的参数,但可变参数 1 的类型为"int *"
- 如何使用OpenSSL API从其PEM格式字符串中读取RSA公钥
- C 格式字符串宏
- C++等效于 C 的格式字符串
- 如何使用 C++ 中的 rapidjson 库从 json 格式字符串中获取值
- _vsnprintf和_vsnprintf_s的格式字符串中的可用百分比字符
- 如何将格式字符串发送到iostream
- 跨平台格式字符串
- 使用 swprintf() 打印"0x0"的格式字符串应该是什么?