1

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;
}
3
  • 3
    Time to read the man page? It is quite involved. The man pages should always be your first reference. Commented Feb 20, 2017 at 22:14
  • The difference between specified width and specified precision for strings. See the documentation for printf, and read it carefully. When using s, "Precision specifies the maximum number of bytes to be written." Commented Feb 20, 2017 at 22:15
  • Yes read the man page. It tells you in specific detail: "...or the maximum number of characters to be printed from a string for s and S conversions" Commented Feb 20, 2017 at 22:15

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.