The Boost Format documentatio n 说:
One of its goal is to provide a replacement for printf, that means format can parse a format-string designed for printf, apply it to the given arguments, and produce the same result as printf would have.
当我使用相同的格式字符串比较 boost:format 和 printf 的输出时,我得到了不同的输出。在线例子是here
#include <iostream>
#include <boost/format.hpp>
int main()
{
boost::format f("BoostFormat:%d:%X:%c:%d");
unsigned char cr =65; //'A'
int cr2i = int(cr);
f % cr % cr % cr % cr2i;
std::cout << f << std::endl;
printf("Printf:%d:%X:%c:%d",cr,cr,cr,cr2i);
}
输出是:
boost 格式:A:A:A:65
printf: 65:41:A:65
区别在于当我想将 char 显示为整数类型时。
为什么会有差异?这是错误还是需要的行为?
最佳答案
这是预期的行为。
在boost manual它是关于您使用的经典类型规范的:
But the classical type-specification flag of printf has a weaker meaning in format. It merely sets the appropriate flags on the internal stream, and/or formatting parameters, but does not require the corresponding argument to be of a specific type.
另请注意,在 stdlib-printf 调用中,所有 char
参数都是自动的
由于可变参数调用,转换为 int
。所以生成的代码与:
printf("Printf:%d:%X:%c:%d",cr2i,cr2i,cr2i,cr2i);
此自动转换不是使用 %
运算符完成的。
关于c++ - 为什么 Boost Format 和 printf 在相同的格式字符串上表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823008/