C语言 如何使用 printf 打印非空终止字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2137779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:15:50  来源:igfitidea点击:

How do I print a non-null-terminated string using printf?

cstringprintf

提问by Mike

How can I print a non-null-terminated string using printf, assuming that I know the length of the string at runtime?

假设我在运行时知道字符串的长度,如何使用 printf 打印非空终止字符串?

回答by kennytm

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 %.123sformat. This means the output length is at most 123 chars. The 123could be replaced by *, so that the length will be taken from the argument of printf instead of hard-coded.

在 C 中,您可以指定%.123s格式输出的最大长度。这意味着输出长度最多为 123 个字符。所述123可以被替代*,从而使长度将从printf的的参数,而不是硬编码要采取。

Note that this assumes the stringdoes not contain any interior null bytes (\0), as %.123sonly constrains the maximumlength not the exactlength, and strings are still treated as null-terminated.

请注意,这假定string不包含任何内部空字节 (\0),因为%.123s仅限制最大长度而不是确切长度,并且字符串仍被视为以空字符结尾。

If you want to print a non-null-terminated string with interior null, you cannot use a single printf. Use fwriteinstead:

如果要打印内部为空的非空终止字符串,则不能使用单个 printf。使用fwrite来代替:

fwrite(string, 1, length, stdout);

See @M.S.Dousti's answerfor detailed explanation.

有关详细说明,请参阅@MSDousti 的回答

回答by M.S. Dousti

The answer provided by @KennyTM is great, but with a subtlety.

@KennyTM 提供的答案很棒,但也很微妙。

In general, if the string is non-null "terminated", but has a null character in the middle, printf("%.*s", length, string);does not work as expected. This is because the %.*sformat string asks printfto print a maximumof lengthcharacters, not exactlylengthcharacters.

一般来说,如果字符串是非空的“终止”,但中间有一个空字符,printf("%.*s", length, string);则不会按预期工作。这是因为%.*s格式字符串要求printf打印最大length人物,不准确length的字符。

I'd rather use the more general solution pointed out by @William Pursell in a comment under the OP:

我宁愿使用@William Pursell 在 OP 下的评论中指出的更通用的解决方案:

fwrite(string, sizeof(char), length, stdout);

Here's a sample code:

这是一个示例代码:

#include <stdio.h>

int main(void) {
    size_t length = 5;

    char string[length];
    string[0] = 'A';
    string[1] = 'B';
    string[2] = 0;        // null character in the middle
    string[3] = 'C';
    string[4] = 'D';

    printf("With printf: %.*s\n", length, string);
    printf("With fwrite: ");
    fwrite(string, sizeof(char), length, stdout);
    printf("\n");

    return 0;
}

Output:

输出:

With printf: AB
With fwrite: AB CD