c++ - 为什么 Boost Format 和 printf 在相同的格式字符串上表现不同

标签 c++ c boost printf boost-format

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/

相关文章:

c++ - 将二进制文件读入 vector 元素的地址

c - 我无法理解这个聊天程序的结果

c++ - basic_socket_acceptor 接口(interface)在 boost 1.66 中发生了变化……这是一个错误吗?

c++ - boost asio有状态服务器设计

c++ - Raku 中 C++ 和 NativeCall 之间的输出不同

c++ - 特殊协议(protocol)的 apache httpd 扩展帮助

c++ - GetSaveFileName/IFileSaveDialog - 用户输入事件/对文件名更改使用react?

c++ - PC与Arduino串口通信

c++ - 在 Debug模式下执行控制台应用程序后,如何让 Visual Studio 暂停?

c++ - C++ 枚举是否从 0 开始?