有谁知道std::printf
在标准 C++ 流上实现功能的库?我正在寻找一个可以让我写的操纵器:
std::cout << ns::stream_printf("There are %d cookies in %d jars\n",
num_cookies, num_jars);
使用变量模板(或它们的模拟)的合理实现甚至可以提供动态类型安全,即格式错误的字符串异常,而不是程序崩溃。
有谁知道std::printf
在标准 C++ 流上实现功能的库?我正在寻找一个可以让我写的操纵器:
std::cout << ns::stream_printf("There are %d cookies in %d jars\n",
num_cookies, num_jars);
使用变量模板(或它们的模拟)的合理实现甚至可以提供动态类型安全,即格式错误的字符串异常,而不是程序崩溃。
Boost.Format可以使用非常接近sprintf
.
从链接的教程:
cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50;
// prints "writing toto, x=40.230 : 50-th try"
http://sf.net/projects/iof上的 iof是 boost 的替代方案。有了它,您可以执行以下操作:
cout << iof::fmt("There are %d cookies in %d jars\n")
<< num_cookies << num_jars;
与 printf 的唯一区别是您始终使用 %s,因为 C++ 知道类型。您在占位符内使用 f、g 等来格式化:
cout << iof::fmt("The number %.2fs is a float value with 2 decimals")
<< 3.141592 << endl;
你也可以做一些整洁的事情,比如
cout << iof::fmt("XYZ coords: %8.4fS %s %s\n")
<< x << y << z;
which will "persist" the format across multiple %s placeholders.
You can also get the equivalent of sscanf and such via its input capability, in case you don't need full regexp parsing:
float a, b, c;
cin >> iof::fmt("%fs,%fs,%fs") >> a >> b >> c;