Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a Variable inside a Conversion Specification in C

Tags:

c

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.

like image 640
Chris Jones Avatar asked Mar 19 '26 10:03

Chris Jones


2 Answers

Specify width with an additional parameter:

printf("Hi \"%*s\"\n", length, first);

(note the * instead of field width).

like image 65
nullptr Avatar answered Mar 21 '26 00:03

nullptr


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);
like image 22
Vaughn Cato Avatar answered Mar 20 '26 22:03

Vaughn Cato