如何打印带有嵌入式null的字符串,以便“(null)"替换为'\ 0' [英] How to print a string with embedded nulls so that "(null)" is substituted for '\0'

查看:296
本文介绍了如何打印带有嵌入式null的字符串,以便“(null)"替换为'\ 0'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用memcpy()组成的字符串,当扩展时,它看起来像这样:

I have a string I composed using memcpy() that (when expanded) looks like this:

char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";

我想打印字符串中的每个字符,如果字符为空,请打印出"(null)"来替代'\ 0'.

I would like to print every character in the string, and if the character is null, print out "(null)" as a substitute for '\0'.

如果我使用puts()或printf()之类的函数,它将以第一个null结尾并打印出来

If I use a function like puts() or printf() it will just end at the first null and print out

AAAA

那么如何在不将其解释为字符串末尾的情况下打印出实际的单词(null)"呢?

So how can I get it to print out the actual word "(null)" without it interpreting it as the end of the string?

推荐答案

您必须自己进行映射.如果您愿意,那就是.在C中,字符串以null终止.因此,如果您使用格式化的输出函数(例如printfputs)并要求它打印字符串(通过格式说明符%s),它将在它遇到第一个null时立即停止打印str. . C中没有null词.如果您确切地知道str中有多少个字符,则最好遍历它们并单独打印出字符,用所选的助记符代替0.

You have to do that mapping yourself. If you want to, that is. In C, strings are null-terminated. So, if you use a formatted output function such as printf or puts and ask it to print a string (via the format specifier %s) it'd stop printing str as soon as it hits the first null. There is no null word in C. If you know exactly how many characters you have in str you might as well loop over them and print the characters out individually, substituting the 0 by your chosen mnemonic.

草案说出7.21.6.1/8:

The draft says 7.21.6.1/8:

p 参数应为指向void的指针.指针的值是 转换为一系列打印字符, 实现定义的方式.

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

但是,以下内容:

$ cat null.c
#include <stdio.h>
int main() {
 printf("%p\n", (void *)0);
}

产生:

00000000

在gcc 4.6和clang 3.2上.

on both gcc 4.6 and clang 3.2.

但是,在更深入的研究中:

However, on digging deeper:

$ cat null.c
#include <stdio.h>
int main() {
 printf("%s\n", (void *)0);
}

确实可以产生所需的输出:

does indeed produce the desired output:

(null)

在gcc和clang上.

on both gcc and clang.

请注意,该标准并不强制执行以下操作:

Note that the standard does not mandate this:

s 如果没有l长度修饰符,则参数应为指针 到字符类型数组的初始元素.280)个字符 从数组中写入直到(但不包括)终止符 空字符.如果指定了精度,则不超过 字节被写入.如果未指定精度或更高 比数组的大小大,该数组应包含一个空字符.

s If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.280) Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

依靠这种行为可能会导致意外!

Relying on this behavior may lead to surprises!

这篇关于如何打印带有嵌入式null的字符串,以便“(null)"替换为'\ 0'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆