Итак, я немного в тупике. Согласно 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;
}
Он выводит
test: one two three four test: two three four test: three four test: four
Когда я думаю, что должен получить
test: one test: two test: three test: four
Я что-то делаю не так, или страница руководства просто мне лжет?
К вашему сведению: я знаю, что могу (в общем) взломать строку и вставить временный '\0'
для завершения строки (кроме случаев, когда это char const *
, как здесь, мне пришлось бы скопировать его вместо этого), но это PITA (особенно если я Я пытаюсь напечатать две половины чего-либо в одном printf), и я хочу знать, почему точность игнорируется.