I want to print a string with exactly 20 characters regardless of whether the length of the str is shorter or longer. Right now I am using:
printf(" s:",r->str);
This doesn't shorten the string if it is too long but it does add the padding correctly. How can achieve this?
CodePudding user response:
You want the printf
width and precision format modifiers for strings.
You are already familiar with the width modifier, %Ns
, where N
is the minimum field with to consume. The precision modifier (yes, syntax-similar to floating point precision modifier), establishes the maximum number of characters to consume. %.Ms
, where M
is the maximal number of characters to consume. And the money question, can you use both? Yes, you can: %N.Ms
#include <stdio.h>
int main()
{
char str[] = "1234567890";
printf("%5.5s\n", str);
}
Output
12345
Note that one/both of these can be dynamically set by using a *
rather than a fixed width, and providing the dynamic length as a preamble argument in the printf
argument list. An (admittedly boring) example is shown below:
#include <stdio.h>
int main()
{
char str[] = "1234567890";
for (int i=2; i<=5; i)
{
for (int j=2; j<=5; j)
printf("%%%d.%%%d : %*.*s\n", i, j, i, j, str);
}
}
Output
%2.%2 : 12
%2.%3 : 123
%2.%4 : 1234
%2.%5 : 12345
%3.%2 : 12
%3.%3 : 123
%3.%4 : 1234
%3.%5 : 12345
%4.%2 : 12
%4.%3 : 123
%4.%4 : 1234
%4.%5 : 12345
%5.%2 : 12
%5.%3 : 123
%5.%4 : 1234
%5.%5 : 12345