0

我有以下代码:

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

但现在输出看起来像:

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

如何使0302站在柱子的中心?

4

5 回答 5

2

没有直接的方法可以使文本居中。您必须结合几个元素:

  1. 算出你有多少位数。
  2. 计算数字前后需要多少个空格。
  3. 打印:printf("%*s%d%*s", spaces_before, "", num, spaces_after, "");

%*s使用两个参数 - 第一个是长度,第二个是要打印的字符串。在这里,我告诉它打印一个给定宽度的空字符串,它只打印所需数量的空格。

于 2013-07-03T09:24:19.453 回答
1

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

printf("+--------------+----------\n"
        " Postal number| Tele\n"
        "----------+-----------------+---------------\n"
        "%8u             |      %3u", number, tele);
于 2013-07-03T09:04:41.850 回答
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;
}
于 2013-07-03T10:20:56.373 回答
0
 int number=5;
 int tele=10;
 printf("+--------------+----------\n"
    " Postal number| Tele\n"
    "----------+-----------------+---------------\n"
   "\t%u     |      \t%u\n", number, tele);
于 2013-07-03T09:24:20.627 回答
0

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

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

希望能帮助到你 !

于 2013-07-19T23:40:10.690 回答