Jason Yang-Jhu Chen
Jason Yang-Jhu Chen

Reputation: 37

printf function string printout argument usage

I'm currently encountering this problem. I wanted to print out the # as I defined in the code block below, thing is when I pass the printf argument as printf("%*s\n", x, BORDER), it prints out all the # I defined at the beginning. However, when I write it as printf("%.*s\n", x, BORDER) then it prints out just as many # as I wanted. Can someone tell me what's the difference that triggered this problem? I know width and precision stand an important role when it comes to float number printout, but this is string print out...

#include <stdio.h>
#include <string.h>

#define BORDER "############################################"

int main(void) {
    char word[26];
    int x;

    scanf("%25s", word);
    x = strlen(word) + 2;
    printf("x = %d\n", x);
    printf("%*s\n", x, BORDER);
    printf("#%s#\n", word);    
    printf("%*s\n", x, BORDER);

    return 0;
}

Upvotes: 1

Views: 61

Answers (1)

chqrlie
chqrlie

Reputation: 144695

Here is the difference between the two syntaxes:

  • The optional field width passed with %*s specifies the minimum width to print for the string. If the string is shorter, extra spaces will be printed before the string.

  • The optional precision passed with %.*s specifies to maximum number of characters to print from the string argument.

In your case, you want to limit the number of characters to print from the BORDER string, so you should use the %.*s format:

printf("%.*s\n", x, BORDER);

Note however that this approach is not generic as you must keep to definition of BORDER in sync with the array size.

Here is a different approach:

#include <stdio.h>
#include <string.h>

int main(void) {
    char word[26];

    if (scanf("%25s", word) == 1) {
        int x = strlen(word) + 2;
        char border[x + 2];

        memset(border, '#', x);
        border[x] = '\0';

        printf("x = %d\n", x);
        printf("%s\n#%s#\n%s\n", border, x, border);
    }    
    return 0;
}

Upvotes: 2

Related Questions