#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    75
    Rep Power
    2

    Width field for scanf and printf


    I was playing with width field for printf and scanf in C but I'm rather confused by it.

    I tried the following code :-
    Code:
    int N = 24;
    printf ("%1d", N);
    It prints 24 but as far as I understood it should only print 2 as I told to print only 1 character.
    Now this code :-
    Code:
    int N;
    scanf ("%1d", &N);
    printf ("%d", N);
    In this if I input 24 it prints 2 as it only scans 1 character.

    Why didn't the first code work?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    The width in printf is working correctly and doing exactly what it's supposed to do.

    Read The Manual (RTFM!).

    From one of literally thousands of man pages for printf that are on-line (this from one at http://linux.die.net/man/3/printf) -- underlining added by me:
    The field width

    An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a '-' flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

IMN logo majestic logo threadwatch logo seochat tools logo