【发布时间】:2011-08-25 01:56:12
【问题描述】:
打印字符串时是否有一些花哨的 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);
}
【问题讨论】:
-
void main()是错误的。将其设为int main()用于 C++,int main(void)用于 C。(由于您使用的是<cstdio>和<cstring>,显然您使用的是 C++,所以它应该是int main()。) -
您的示例非常明显地融合了 C 和 C++,这很好,但您可以期待收到各种答案。
-
确实,我使用了 C++ 和 c 的混合。 C++ 非常适合让事情快速进行。 C 速度很快。由于使用了 printf,我标记了“c”。