2

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sevs
  • 73
  • 1
  • 6
  • How will you center if you have an odd number of spaces remaining after accounting for all the characters in your number? – merlin2011 Jun 02 '14 at 23:22
  • That is, what is your definition of "centering" in that case? – merlin2011 Jun 02 '14 at 23:23
  • http://stackoverflow.com/questions/2461667/centering-strings-with-printf – merlin2011 Jun 02 '14 at 23:31
  • Do you want the numbers organized such that the largest number is centred and the others are right aligned with the largest number, or is each number individually centred? Is the overall width determined after finding the maximum, or is it determined beforehand? Your example could support either definition. – Jonathan Leffler Jun 03 '14 at 00:25
  • Sorry, guys, i just realized that i only need to right align text! I'm starting to learn C and my professor wasn't very clear on what he wanted. Anyway, it was a very simple task, sorry to make such a stupidness... And sorry about my english, im not a native speaker. – sevs Jun 03 '14 at 20:28

1 Answers1

5

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|
user2303197
  • 1,271
  • 7
  • 10