6

How do I append blank spaces to the end of a string using printf?

I can't find any examples where spaces are appended to the right. A similar question I found use printf to add spaces to the left of the string instead.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
godMode
  • 371
  • 1
  • 3
  • 9

1 Answers1

6

Use negative numbers to left-align (i.e. "pad" to the right).

#include <stdio.h>
int main() {
    const char *s = "hello";
    printf("%30sworld\n", s);
    printf("%-30sworld\n", s);
}

This prints

                         helloworld
hello                         world
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • cool, the number of chars are going to be variable so can i pass something like this into printf? `"%-*", s, number` sorry, again i'm not on my compile PC. – godMode Mar 13 '12 at 00:53
  • whoops i just realized i can just turn the number into a negative number like this: number * -1. i'm sure this will work, will let you know when i get home. – godMode Mar 13 '12 at 01:01