小编Cha*_*had的帖子

printf一个带空值的缓冲区

是否有一些花哨的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 …
Run Code Online (Sandbox Code Playgroud)

c c++ printf packet

2
推荐指数
1
解决办法
3655
查看次数

标签 统计

c ×1

c++ ×1

packet ×1

printf ×1