1

I've managed to print left-aligned padded columns when the output is static like this:

int col = 40;
printf("%-*s", col, "padded column");
printf("after the column\n");

I'm trying to do the same when the string is not static but formatted with a variable, ie:

int col = 40;
int var1 = 200;
printf("???", col, var1, " padded column");
printf("after the column\n");

Where the expected output would be, for example:

200 padded column                  after padded column
2
  • What is the problem? Why is %d not good enough? Commented Sep 24, 2015 at 9:11
  • @user694733 Well my problem is that this printf("%-*s", col, "%d padded column", var1); is of course not valid, and this printf("%d%-*s", var1, col, " padded column"); doesn't generate a total width of col. Commented Sep 24, 2015 at 9:18

1 Answer 1

1

You need to generate text in 2 parts:

char paddedColText[100];
snprintf(paddedColText, sizeof paddedColText, "%d padded column", var1);
printf("%-*s", col, paddedColText);

or, alternative:

col -= printf("%d", var1); // Returns string length
printf("%-*s", col, " padded column");

But keep in mind that printf can return negative error code, so checking the return value before using is a good idea.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.