Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf seems to be ignoring string precision

So, I'm a bit stymied. According to man 3 printf on my system, the string format "%5s" should use the specified precision to limit the number of characters printed from the string argument given.

% 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.

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;
}

It outputs

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

When I think I should be getting

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

Am I doing something wrong, or is the man page just lying to me?

FYI: I know I could (in general) hack the string, and insert temporary '\0' to terminate the string (except when it's a char const *, like here, I'd have to copy it instead), but it's a PITA (especially if I'm trying to print two halves of something in the same printf), and I want to know why the precision is being ignored.

like image 252
rampion Avatar asked Dec 02 '22 07:12

rampion


1 Answers

You're not setting the precision, you're setting the field width. The precision always starts with a . in the format specification.

printf("test: %.3s\n", test);
like image 161
CB Bailey Avatar answered Dec 04 '22 23:12

CB Bailey