Bill
Bill

Reputation: 19308

NSLog(@"%-20s %-32s", [theCard.name UTF8String]) %-32s means?

I am studying Objective-C, I know NSLog to print out, But I am lost with this %-20s %-32s.

What is this -20s and -32s doing here

  -(void) list
    {
    NSLog (@"======== Contents of: %@ =========", bookName);
    for ( AddressCard *theCard in book )
    NSLog (@"%-20s %-32s", [theCard.name UTF8String],
    [theCard.email UTF8String]);
    Array Objects 339
    NSLog (@"==================================================");
    }
    @

====================================
|                                  |
| Tony Iannino                     |
| [email protected]     |
|                                  |
|                                  |
|                                  |
| O O                              |
====================================

Upvotes: 0

Views: 811

Answers (2)

user529758
user529758

Reputation:

NSLog() understands printf() format strings with some extensions, so you can look up in the documentation of printf() what this does:

Each conversion specification is introduced by the '%' character [XSI] or by the character sequence "%n$" [...]

  • Zero or more flags [...]
  • An optional minimum field width [...]
  • An optional precision [...]
  • An optional length modifier [...]
  • A conversion specifier character that indicates the type of conversion to be applied.

[...]

The flag characters and their meanings are:

[...]

-: The result of the conversion shall be left-justified within the field. The conversion is right-justified if this flag is not specified. [...]

The conversion specifiers and their meanings are:

[...]

s: The argument shall be a pointer to an array of char. Bytes from the array shall be written up to (but not including) any terminating null byte. If the precision is specified, no more than that many bytes shall be written. If the precision is not specified or is greater than the size of the array, the application shall ensure that the array contains a null byte.

[...]

So, what this conversion does is printing an array of const char, printing 20 and 32 characters, respectively, padding it with spaces to the right in order left justufication to take effect.

Upvotes: 1

Joni
Joni

Reputation: 111349

They are printf formatting specifiers to print a string of 20 and 32 characters, filled with blanks on the right.

% start of the specifier
- align the field to left instead of right
32 width of field
s type of field is string

Full documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

Upvotes: 3

Related Questions