c++ - printf 带有空值的缓冲区

标签 c++ c printf packet

是否有一些奇特的 printf 语法可以在打印字符串时忽略空值?

示例用例:打印包含一堆空终止字符串的网络数据包。

我的测试代码来说明这个问题:

#include <cstdio>
#include <cstring>

void main()
{
    char buffer[32];
    const char h[] = "hello";
    const char w[] = "world";
    const int size = sizeof(w) + sizeof(h);

    memcpy(buffer, h, sizeof(h));
    memcpy(buffer + sizeof(h), w, sizeof(w));

    //try printing stuff with printf
    printf("prints only 'hello' [%s]\n",buffer);
    printf("this prints '<bunch of spaces> hello' [%*s]\n",size,buffer);
    printf("and this prints 'hello' [%.*s]\n",size,buffer);

    //hack fixup code
    for(int i = 0; i < size; ++i)
    {
        if(buffer[i] == 0)
            buffer[i] = ' ';
    }
    printf("this prints 'hello world ' [%.*s]\n",size,buffer);
}

最佳答案

printf 假定字符串是 c 风格的(即以空字符结尾)。您需要执行以下操作之一:

1)使用ostream的write方法(C++风格)

2) 使用write 命令(来自unistd.h,C 风格)

3) 遍历每个字符并打印。

当我调试数据包时,通常我会使用 %02hhx 格式打印出每个字符,以确保我看到准确的代码(没有任何关于将空字符打印到屏幕的怪癖)

关于c++ - printf 带有空值的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7184303/

相关文章:

c - 在 MSVC 2010 项目中添加 .dll 文件的正确方法是什么

c - 负值转换为其对应的正值

c - 在 C 中以更高的精度存储数字

C : Nothing to be done for 'all' Hello word

c - 为什么这个 printf 语句没有被执行

C:没有打印出我想要的内容

c++ - 在编译时选择随机数分布

c++ - 使用 DirectX 11 API 读取 HLSL 语义和注释?

c++ - 渲染到 FBO 不起作用,gDEBugger 另有说法

c++ - 没有在此范围内声明?