I have an assignment and I was trying to figure out two ways to do one thing. I have the code here
#include <stdio.h>
int main(void)
{
char first[10];
int length;
printf("what is your first name?\n");
scanf("%s", &first);
length = strlen(first)+3;
printf("%d\n", length);
printf("Hi \"%s\"\n", first);
printf("Hi \"%20s\"\n", first);
printf("Hi \"%-20s\"\n", first);
printf("Hi \"%8s\"\n", first);
return 0;
}
Fairly simple overall. However, the last statement
printf("Hi \"%8s\"\n", first);
was something I wanted to do differently. The criteria for the that statement was to print it in a field 3 characters wider than the name. With my name Being Chris, I know that being 8 Characters wide accomplishes this, however, I was wondering if I could use the length variable I have created and do something like this below so that I don't have to know the length of the name ahead of time.
printf("Hi \"%[Length]s\"\n", first);
I know that doesn't work, but I think it gets the idea across.
Specify width with an additional parameter:
printf("Hi \"%*s\"\n", length, first);
(note the * instead of field width).
You can use an asterisk instead of a specific with value to indicate that the width will be specified as another parameter:
printf("Hi \"%*s\"\n",length,first);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With