32

By default, printf() seems to align strings to the right.

printf("%10s %20s %20s\n", "col1", "col2", "col3");
/*       col1                 col2                 col3 */

I can also align text to the left like this:

printf("%-10s %-20s %-20s", "col1", "col2", "col3");

Is there a quick way to center text? Or do I have to write a function that turns a string like test into (space)(space)test(space)(space) if the text width for that column is 8?

10 Answers 10

36

printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect)

void f(char *s)
{
        printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,"");
}
int main(int argc, char **argv)
{
        f("uno");
        f("quattro");
        return 0;
}
4
  • I tested this in some C++ code I wrote to create table, and it was truncating valid text, and I had to figure out why. I've provided an alternative answer based on how I resolved it.
    – clearlight
    Nov 25, 2018 at 15:57
  • Correct, indeed I warned that the solution is "not perfect", due to hard coded constants it contains. My goal was just to give a hint, your solution completes the idea. Nov 26, 2018 at 18:21
  • The * expects an int, strlen() will return size_t. This function causes UB when SIZE_MAX>INT_MAX. Possible solution: Change it to (int) ((10+strlen(s)/2)&INT_MAX) Aug 13, 2021 at 20:36
  • Correct. In most cases casting strlen directly to int is enough. It's unlikely that a string that was meant to be centered exceeds INT_MAX in length. Aug 23, 2021 at 7:24
14

@GiuseppeGuerrini's was helpful, by suggesting how to use print format specifiers and dividing the whitespace. Unfortunately, it can truncate text.

The following solves the problem of truncation (assuming the field specified is actually large enough to hold the text).

void centerText(char *text, int fieldWidth) {
    int padlen = (fieldWidth - strlen(text)) / 2;
    printf("%*s%s%*s\n", padLen, "", text, padlen, "");
} 
4
  • 3
    note that the resulting total width will be different depending on if fieldWidth - strlen(text) is even or odd
    – rtpax
    Feb 21, 2019 at 16:38
  • added a modified version that always prints fieldWidth characters (e.g. for use in tables etc.)
    – zeawoas
    Dec 4, 2019 at 14:29
  • 1
    The behavior is implementations defined when the result of (fieldWidth - strlen(text)) / 2; is out of the range of an int. Which can be the case when SIZE_MAX>INT_MAX and strlen(text)>fieldWidth, causing (fieldWidth - strlen(text)) == SIZE_MAX-(strlen(text)-fieldWidth-1). Aug 13, 2021 at 20:43
  • @12431234123412341234123 Reminds me of the old adage "Just because you can do something, doesn't mean you should."
    – clearlight
    Aug 16 at 0:28
2

There is no printf() format specifier to centre text.

You will need to write your own function or locate a library which provides the functionality that you're looking for.

1
  • 9
    Your opportunity to go the extra 9 yards to provide a solution, eh?
    – clearlight
    Nov 25, 2018 at 15:14
2

You may try write own function for this problem.

/**
 * Returns a sting "str" centered in string of a length width "new_length".
 * Padding is done using the specified fill character "placeholder".
 */
char *
str_center(char str[], unsigned int new_length, char placeholder)
{
    size_t str_length = strlen(str);

    // if a new length is less or equal length of the original string, returns the original string
    if (new_length <= str_length)
        return str;

    char *buffer;
    unsigned int i, total_rest_length;

    buffer = malloc(sizeof(char) * new_length);

    // length of a wrapper of the original string
    total_rest_length = new_length - str_length;

    // write a prefix to buffer
    i = 0;
    while (i < (total_rest_length / 2)) {
        buffer[i] = placeholder;
        ++i;
    }
    buffer[i + 1] = '\0';

    // write the original string
    strcat(buffer, str);

    // write a postfix to the buffer
    i += str_length;
    while (i < new_length) {
        buffer[i] = placeholder;
        ++i;
    }
    buffer[i + 1] = '\0';

    return buffer;
}

Results:

puts(str_center("A", 0, '-')); // A
puts(str_center("A", 1, '-')); // A
puts(str_center("A", 10, '-')); // ----A-----
puts(str_center("text", 10, '*')); // ***text***
puts(str_center("The C programming language", 26, '!')); // The C programming language
puts(str_center("The C programming language", 27, '!')); // The C programming language!
puts(str_center("The C programming language", 28, '!')); // !The C programming language!
puts(str_center("The C programming language", 29, '!')); // !The C programming language!!
puts(str_center("The C programming language", 30, '!')); // !!The C programming language!!
puts(str_center("The C programming language", 31, '!')); // !!The C programming language!!!
3
  • 1
    Cool that it is c/stdlib only implementation for the standpoint of educating about C but otherwise at least replace the prefix/postfix loops with memcpy() or bcopy()
    – clearlight
    Nov 27, 2018 at 13:55
  • And replace malloc with alloca.. ewww
    – Martin
    Apr 22, 2019 at 15:33
  • alloca wouldn't work in this instance, as the string being returned is in that memory - you don't want it be free'd at the point of the 'str_center' returns! But as Martin points out, as written this leaks memory.
    – ColinB
    Apr 19, 2021 at 10:06
2

There are two solutions, the first is similar to the above, by placing macros in printf, and the second is a custom macro, which calculates the length of the formatted string in advance through snprintf, and then calls the printf function to output.

#include <stdio.h>
#include <string.h>

#define LEFT(str, w) \
    ({int m = w + strlen(str); m % 2 ? (m + 1) / 2 : m / 2;})

#define RIGHT(str, w) \
({ int m = w - strlen(str); m % 2 ? (m - 1) / 2 : m / 2; })

#define STR_CENTER(str, width) \
    LEFT(str, width), str, RIGHT(str, width), ""

#define PRINTF_CENTER(width, start, fmt, end, ...) ({ \
    int n = snprintf(NULL, 0, fmt, __VA_ARGS__);     \
    int m = width - n;                               \
    int left = m % 2 ? (m + 1) / 2 : m / 2;          \
    int right = m % 2 ? (m - 1) / 2 : m / 2;         \
    printf(start "%*s" fmt "%*s" end, left, "",      \
           __VA_ARGS__, right, "");                  \
})

#define MYFORMAT_CENTER(width, fmt, ...)  \
    PRINTF_CENTER(40, "[", fmt  , "]\n", __VA_ARGS__)

int main(int argc, char const *argv[])
{
    printf("%*s%*s\n\n", STR_CENTER("--- Hello World ---", 40));
    printf("[%*s%*s]\n", STR_CENTER("I am okay today", 40));
    
    MYFORMAT_CENTER(40, "%d, e is %f", 1, 2.71828);
    MYFORMAT_CENTER(40, "%d, pi is %f", 2, 3.1415926);
    MYFORMAT_CENTER(40, "%s %d.", "This is such a long string that it exceeds the given size:", 40);

    return 0;
}

Output:

           --- Hello World ---

[             I am okay today            ]
[            1, e is 2.718280            ]
[            2, pi is 3.141593           ]
[           This is such a long string that it exceeds the given size: 40.           ]
1

Ill drop my 2 cents after dealing with similar issue of trying to center a table headers in a row with printf.

The following macros will need to be printed before/after the text and will align regardless of the length of the text itself. Notice that if we have odd length strings, we will not align as should(because the normal devision will result in missing space). Therefor a round up is needed, and I think this is the elegant way to solve that issue:

#define CALC_CENTER_POSITION_PREV(WIDTH, STR) (((WIDTH + ((int)strlen(STR))) % 2) \
       ? ((WIDTH + ((int)strlen(STR)) + 1)/2) : ((WIDTH + ((int)strlen(STR)))/2))
#define CALC_CENTER_POSITION_POST(WIDTH, STR) (((WIDTH - ((int)strlen(STR))) % 2) \
       ? ((WIDTH - ((int)strlen(STR)) - 1)/2) : ((WIDTH - ((int)strlen(STR)))/2))

Usage example:

printf("%*s%*s" , CALC_CENTER_POSITION_PREV(MY_COLUMN_WIDTH, "Header")
                , "Header"
                , CALC_CENTER_POSITION_POST(MY_COLUMN_WIDTH, "Header"), "");
0

Yes, you will either have to write your own function that returns " test " etc, e.g.

printf("%s %s %s", center("col1", 10), center("col2", 20), center("col3", 20));

Or you have a center_print function, something like the following:

void center_print(const char *s, int width)
{
        int length = strlen(s);
        int i;
        for (i=0; i<=(width-length)/2; i++) {
                fputs(" ", stdout);
        }
        fputs(s, stdout);
        i += length;
        for (; i<=width; i++) {
                fputs(" ", stdout);
        }
}
2
  • 1
    The first suggestion: How can this be impl'd without leaking memory?
    – kevinarpe
    Mar 31, 2017 at 13:57
  • If you preallocate some buffers based on some criteria that does not seem unreasonable (like for instance no more than 20 arguments will be centred for one printf, and none of the centred results will be longer than 200 bytes), you could let the center function just rotate buffers on each invocation.
    – hlovdal
    Apr 2, 2017 at 15:18
0

A more compact version of PADYMKO's function above (which still leaks memory):

char *str_center(char str[], unsigned int new_length, char placeholder)
{
    size_t str_length = strlen(str);
    char *buffer;
    /*------------------------------------------------------------------
     * If a new length is less or equal length of the original string, 
     * returns the original string 
     *------------------------------------------------------------------*/
    if (new_length <= str_length)
    {
        return(str);
    }
    buffer = malloc(sizeof(char) * (new_length + 1));
    memset(buffer, placeholder, new_length);
    buffer[new_length] = '\0';
    bcopy(str, buffer + (( new_length - str_length) / 2), str_length);
    return(buffer);
}

This sets the whole of newly allocated buffer to the padding character, null terminates that, and then drops the string to be centred into the middle of the buffer - no loops, or keeping track of where to copy to..

0

If you want to be able to use a printf() format string for that and you accept to be limited to the GNU clib, you can extend printf() with your own conversion specifier for centering a string with. Add the conversion specifier with register_printf_function(). See here for the documentation: https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html The other answers already provide you with a solution on how to manually print a string in the center, which you still need when using your own conversion specifier.

-2

You can use either of the following two options:

char name[] = "Name1";

//Option One
printf("%*s", 40+strlen(name)/2, name, 40-strlen(name)/2, "");
puts("");//skip one line
//Option two
printf("%*s", 40+strlen("Name2")/2, "Name2", 40-strlen("Name2")/2, "");

The output is:

Name1(center)
Name2(center)

1
  • 1
    First of all, this looks like a ripoff of Giuseppe's answer, and, secondly, you have more printf() arguments than you have format specifiers to accommodate them. Did you even test this?
    – clearlight
    Nov 25, 2018 at 15:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.