1

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("%20s:",r->str); 

This doesn't shorten the string if it is too long but it does add the padding correctly. How can achieve this?

0

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.