如何打印用printf一个非空结尾的字符串? [英] How do I print a non-null-terminated string using printf?
问题描述
我如何用printf,假设我知道在运行时的字符串长度打印一个非空结尾的字符串?
的printf(%* S,长度字符串);
与其他ARGS一起使用:
的printf(整数=%d个,字符串=%* S,数=%F,整型,长度,字符串,数字);
// ^^^^ ^^^^^^^^^^^^^^
在C语言中,你可以指定最大长度与%的输出。123S
格式。这意味着输出长度最多为123个字符。在 123
可以通过替换*
,这样的长度将从printf函数参数采取的硬件,而不是codeD。
请注意,这个假设字符串
不包含任何内部空字节(\\ 0),如%。123S
只限制了的最大的长度不是的确切的长度,字符串仍视为空值终止。
如果您想打印一个非空结尾的字符串与室内空,则不能使用到一个printf。使用 FWRITE
而不是:
FWRITE(字符串,1,线长,标准输出);
请参阅 @ M.S.Dousti的详细解释答案。
How can I print a non-null-terminated string using printf, assuming that I know the length of the string at runtime?
printf("%.*s", length, string);
Use together with other args:
printf("integer=%d, string=%.*s, number=%f", integer, length, string, number);
// ^^^^ ^^^^^^^^^^^^^^
In C you could specify the maximum length to output with the %.123s
format. This means the output length is at most 123 chars. The 123
could be replaced by *
, so that the length will be taken from the argument of printf instead of hard-coded.
Note that this assumes the string
does not contain any interior null bytes (\0), as %.123s
only constrains the maximum length not the exact length, and strings are still treated as null-terminated.
If you want to print a non-null-terminated string with interior null, you cannot use a single printf. Use fwrite
instead:
fwrite(string, 1, length, stdout);
See @M.S.Dousti's answer for detailed explanation.
这篇关于如何打印用printf一个非空结尾的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!