如何在C中将输出格式化为中心?

时间:2013-07-03 08:59:56

标签: c printf

我有以下代码:

printf("+--------------+----------\n"
        " Postal number| Tele\n"
        "----------+-----------------+---------------\n"
    "%u             |      %u", number, tele);

但是现在输出看起来像:

+--------------+----------
Postal number  | Tele
----------+---------------
03             | 02

如何让0302站在列的中心?

5 个答案:

答案 0 :(得分:2)

没有直接的方法来中心文字。你必须结合几个元素:

  1. 找出你有多少位数。
  2. 计算数字前后所需的空格数。
  3. 打印:printf("%*s%d%*s", spaces_before, "", num, spaces_after, "");
  4. %*s使用两个参数 - 第一个是长度,第二个是要打印的字符串。在这里,我告诉它打印一个给定宽度的空字符串,它只打印所需的空格数。

答案 1 :(得分:1)

只需在格式字符串中添加字段宽度,例如

printf("+--------------+----------\n"
        " Postal number| Tele\n"
        "----------+-----------------+---------------\n"
        "%8u             |      %3u", number, tele);

答案 2 :(得分:1)

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

#define Corner "+"
#define Wall   "|"

typedef enum { left, center, right } position;

int pos_calc(int width, int max_width, position pos){
    int d;
    if((d=max_width - width)< 0)
        return -1;

    switch(pos){
    case   left: return 0;
    case  right: return d;
    case center: return d/2;
    }
}

char *format(char *buff, int width, position pos, const char *data){
    int len = strlen(data);
    int offset = pos_calc(len, width, pos);
    memset(buff, ' ', width);
    buff[width]='\0';
    strncpy(buff + offset, data, len);
    return buff;
}

int main(void){
    unsigned number = 3, tele = 2;
    const int c1w = 15, c2w = 10;
    const char *c1title = "Postal number";
    const char *c2title = "Tele";
    char c1[c1w+1], c2[c2w+1];
    char c1d[c1w+1], c2d[c2w+1];
    char c1line[c1w+1], c2line[c2w+1];

    sprintf(c1d, "%02u", number);
    sprintf(c2d, "%02u", tele);

    memset(c1line, '-', c1w);c1line[c1w] = '\0';
    memset(c2line, '-', c2w);c2line[c2w] = '\0';
    printf("%s%s%s%s%s\n", Corner, c1line, Corner, c2line, Corner);
    format(c1, c1w, center, c1title);
    format(c2, c2w, center, c2title);
    printf("%s%s%s%s%s\n", Wall  , c1, Wall, c2, Wall);
    printf("%s%s%s%s%s\n", Corner, c1line, Corner, c2line, Corner);
    format(c1, c1w, center, c1d);
    format(c2, c2w, center, c2d);
    printf("%s%s%s%s%s\n", Wall  , c1, Wall, c2, Wall);
    printf("%s%s%s%s%s\n", Corner, c1line, Corner, c2line, Corner);

    return 0;
}

答案 3 :(得分:0)

 int number=5;
 int tele=10;
 printf("+--------------+----------\n"
    " Postal number| Tele\n"
    "----------+-----------------+---------------\n"
   "\t%u     |      \t%u\n", number, tele);

答案 4 :(得分:0)

看看我的简单库libtprint:https://github.com/wizzard/libtprint代码非常简单,你应该能够理解它是如何工作的。

基本上你需要的是使用每列的字段宽度并计算对齐偏移。

希望它有所帮助!