sevs
sevs

Reputation: 75

How can I center a number padded with spaces in a fixed width?

I'm trying to do something like this

aligned numbers

But I can't think of something to do it to a generic number. See, I got the maximum space the number can fit in (in this case, the length is 4). But the numbers inside it can have any length less than or equal to (space - 2) so it could fit without touching the borders. I need to center the number in each square no matter how many characters it has.

I tried something like this for the first row:

printf("    ");
for (i = 0; i < columns; i++) {
    printf(" ");
    printf("%*d", length, i);
    printf(" ");
}

But it wouldn't align the number in the center, but on right. What should I do?

Upvotes: 2

Views: 182

Answers (1)

user2303197
user2303197

Reputation: 1316

Something along the lines of this should do (check for errors):

#include <stdio.h>
#include <assert.h>

#define BUFSIZE 20

void print_centered(size_t width, int num) {
  char buffer[BUFSIZE];
  int len;
  int padding_left, padding_right;

  assert(width < BUFSIZE);

  len = snprintf(buffer, BUFSIZE, "%d", num);
  padding_left = (width - len) / 2;
  padding_right = width - len - padding_left;

  (void)snprintf(buffer, BUFSIZE, "%*d%*s", len + padding_left, num, padding_right, padding_right ? " " : "");
  printf("%s", buffer);
}

int main(int argc, char **argv) {
  printf("|");
  print_centered(10, 123);
  printf("|\n");

  printf("|");
  print_centered(10, 1234);
  printf("|\n");

  printf("|");
  print_centered(10, 1234567890);
  printf("|\n");

  return 0;
}

Output:

|   123    |
|   1234   |
|1234567890|

Upvotes: 5

Related Questions