hczaja hczaja - 3 months ago 8
C Question

Displaying the name variable in field for three characters longer than name

C



Question as this way as in the title.
How to display the string variable in field for three characters longer than length of this variable.

code:

char name[10];
int length;

printf("Enter your name: ");
scanf("%s", name);
length = strlen(name) + 3;


And what then?

It should be something like that:

Enter your name:
XXX
" XXX"

Answer

The simplest way to achieve this is to simply add 3 spaces before the %s:

printf("   %s\n", name);

You can also use a variable length specifier (if you want to learn how it works):

printf("%*s\n", length+3, name);