gpt4 book ai didi

c - printf 似乎忽略了字符串精度

转载 作者:太空狗 更新时间:2023-10-29 15:11:11 24 4
gpt4 key购买 nike

所以,我有点受阻。根据我系统上的 man 3 printf,字符串格式 "%5s" 应该使用指定的精度来限制从给定的字符串参数打印的字符数。

% man 3 printfPRINTF(3)                BSD Library Functions Manual                PRINTF(3)NAME     printf, fprintf, sprintf, snprintf, asprintf, vprintf, vfprintf,     vsprintf, vsnprintf, vasprintf -- formatted output conversion...     s       The char * argument is expected to be a pointer to an array of             character type (pointer to a string).  Characters from the array             are written up to (but not including) a terminating NUL charac-             ter; if a precision is specified, no more than the number                          specified are written.  If a precision is given, no null             character need be present; if the precision is not specified, or             is greater than the size of the array, the array must contain a             terminating NUL character.

But my test code doesn't confirm this:

#include <stdio.h>
int main()
{
char const * test = "one two three four";
printf("test: %3s\n", test);
printf("test: %3s\n", test+4);
printf("test: %5s\n", test+8);
printf("test: %4s\n", test+14);
return 0;
}

输出

test: one two three fourtest: two three fourtest: three fourtest: four

当我认为我应该得到

test: onetest: twotest: threetest: four

是我做错了什么,还是手册页在骗我?

仅供引用:我知道我可以(通常)破解字符串,并插入临时的 '\0' 来终止字符串(除非它是 char const * ,就像这里,我不得不复制它),但它是一个 PITA(特别是如果我试图在同一个 printf 中打印两半的东西),我想知道为什么精度被忽略了。

最佳答案

您设置的不是精度,而是字段宽度精度 在格式规范中始终以 . 开头。

printf("test: %.3s\n", test);

关于c - printf 似乎忽略了字符串精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1478115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com