printf似乎忽略了字符串精度

ram*_*ion 4 c printf string-formatting

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

% man 3 printf
PRINTF(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.

但是我的测试代码没有证实这一点:

#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;
}
Run Code Online (Sandbox Code Playgroud)

它输出

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

当我想我应该得到

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

我做错了什么,还是手册对我说谎?

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

CB *_*ley 19

您没有设置精度,而是设置字段宽度.该精度总是以开始.格式规范.

printf("test: %.3s\n", test);
Run Code Online (Sandbox Code Playgroud)

  • ****捂脸.谢谢! (3认同)