是否有一些奇特的 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/