简体   繁体   中英

What does “%.*s” mean as a format specifier in printf?

Can anyone tell me what this means: "%.*s"

For example, it is in use here:

  sprintf(outv->deliveryAddressCity, 
          "%.*s",
          sizeof(outv->deliveryAddressCity)-1,
          mi->deliveryAddressCity);

%.*s means print the first X number of characters from the following buffer . In this case, print the first sizeof(outv->deliveryAddressCity) - 1 characters from mi->deliveryAddressCity , preventing writing beyond the bounds of outv->deliveryAddressCity .

A shorter example:

printf("%.*s", 4, "hello world");

would print hell .

Maybe you can get it with this example:

printf("%.*s", 3, "abcdef");

prints "abc".

The width and precision formatting parameters may be omitted, or they can be a fixed number embedded in the format string, or passed as another function argument when indicated by an asterisk "*" in the format string. For example printf("%*d", 5, 10) will result in " 10" being printed, with a total width of 5 characters, and printf("%.*s", 3, "abcdef") will result in "abc" being printed.

(It was really easy to find it on a search engine...)

It is most commonly used when you have a string that is not null terminated, and the length is stored elsewhere.

For example:

{
    char* regular_string = "Hello World";  // This string has a null-Terminator.

    char untermed_string[11];
    int len;

    // Specifically make untermed string so it is NOT null-terminated.
    memcpy(untermed_string, regular_string, 11);
    len = 11;

    printf("The string is %.*s\n", len, untermed_string); // This will still print the proper data!
    printf("The start of the string is %.*s\n", 5, untermed_string); // This will only print "Hello".
}

this is a format-specifier, which takes 2 values from the stack, the first is the size, the second the value.

The .-notation: atleast-length.maxlength (so ".*" means: max * characters)

it helps you to print the part of the string . u can specify to what length u have to print the string . example : printf("%.*s", 5, ,"rahul subedi") output: rahul

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM