0

I know this maybe isn't the place to post but, I did make what I needed work but i'm having difficulty understanding how it works

//Variables
char FirstName[100];
char LastName[100];
//Coding
printf("Please enter your first name: ");
scanf("%s", FirstName);
printf("Please enter your last name: ");
scanf("%s", LastName);
printf("%s %s\n", FirstName, LastName);
printf("%d %*s %d", strlen(FirstName),(strlen(FirstName)-2),"", strlen(LastName));

I want to make it output the first and last name, and then under that, it displays how long each string is. I made it also put the number at the start of the string and it works, but i'm not sure how it works exactly, can somebody explain how the last printf works? mostly the %*s part?

VallyMan
  • 145
  • 5

1 Answers1

2
  • The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

e.g: printf("%*s", 8, value); is equivelant to printf("%8s", value);.

Narrated from @Ondrej

#include <stdio.h>

int main() {
    int precision = 8;
    int biggerPrecision = 16;
    const char *greetings = "Hello world";

    printf("|%.8s|\n", greetings);
    printf("|%.*s|\n", precision , greetings);
    printf("|%16s|\n", greetings);
    printf("|%*s|\n", biggerPrecision , greetings);

    return 0;
}

we get the output:

|Hello wo|
|Hello wo|
|     Hello world|
|     Hello world|
snr
  • 13,515
  • 2
  • 48
  • 77