Reputation: 109
I need help on this exercise from C Primer Plus.
Write a program that requests your first name and does the following with it: Prints it in a field three characters wider than the name
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
int p,v=0;
printf("Enter your first name: \n");
scanf("%s",a);
p= strlen(a);
v==p+3;
printf("%s",a);
}
I cant figure out how what to use as a modifier for the width what should I add in between % and s?
Upvotes: 0
Views: 1420
Reputation: 6003
Here is one way to do it:
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
printf("Enter your first name: \n");
scanf("%s",a);
printf("[%-*s]", (int)(3 + strlen(a)), a);
return(0);
}
The printf() function can do it all.
From the question code, it is clear that "%s
" as a format string is understood.
A format string of "%*s
" allows the caller to place the (space-padded) width to be specified. For example:
printf("%*s", 10, "Hello");
The above will print "Hello
" (as expected), in a 10-character frame. Hence, the command above actually prints: " Hello
".
To put the spaces on the other side, tell printf() to left-justify the string using:
printf("%-*s", 10, "Hello");
This results in printing: "Hello
"
Upvotes: 3
Reputation: 6070
the goal of this excercise is to read and grok the manual page for printf(). The reading part could only be done by you and there is no shortcut. The format specifier is the most complex chapter in C-Programing (other would say 'pointer'), and it is very wise to know where look things up (man-page) in need of remembering.
When you are done reading, you should have a little (or big) understanding of the format-specifier %s with all its possibilities.
EDITH: when you are done reading, and there is still a question whether to use "%*.*s" or "%s" or "%-.*s" etc., please come back with an updated question.
Upvotes: 5