mannen
mannen

Reputation: 45

Formatting text with printf or printstring in C

I want to print text to a terminal program from a microcontroller, something like this:

printString("textline one here:            OK\n");
printString("textline two here that is longer:             OK\n");
printString("textline three here that is even  longer:             OK\n");

How do I make the text to always be in columns even if I decide to change the textline? To avoid that it looks something like this in the printout in the terminal program:

textline one here:             OK
textline two here that is longer:              OK
textline three here that is even  longer:              OK

and more like this (without having to add extra spaces in text and double check in the terminal program how it looks for every change I do to any text) :

textline one here:                             OK
textline two here that is longer:              OK
textline three here that is even  longer:      OK

Is it easier to use printf or printstring for this?

Upvotes: 2

Views: 438

Answers (1)

dbush
dbush

Reputation: 225817

Rather than including the first part of the text directly in your printf format string, pass it as a parameter to the %s format specifier. You can then add a field width to it to specify the minimum number of characters to print as well as the - flag to tell it to left-justify.

For example, this code:

printf("%-50s %s\n", "textline one here:", "OK");
printf("%-50s %s\n", "textline two here that is longer:", "OK");
printf("%-50s %s\n", "textline three here that is even  longer:","OK");

Prints:

textline one here:                                 OK
textline two here that is longer:                  OK
textline three here that is even  longer:          OK

Also, you could use * instead of an a explicit field width to pass it in as a parameter. That way if you need to change the column width you only do it in one place:

int width = 50;
printf("%-*s %s\n", width, "textline one here:", "OK");
printf("%-*s %s\n", width, "textline two here that is longer:", "OK");
printf("%-*s %s\n", width, "textline three here that is even  longer:","OK");

Upvotes: 2

Related Questions