我有以下代码:
printf("+--------------+----------\n"
" Postal number| Tele\n"
"----------+-----------------+---------------\n"
"%u | %u", number, tele);但现在的输出如下所示:
+--------------+----------
Postal number | Tele
----------+---------------
03 | 02如何让03和02站在柱子的中心?
发布于 2013-07-03 17:24:19
没有直接居中文本的方法。你必须组合几个元素:
printf("%*s%d%*s", spaces_before, "", num, spaces_after, "");
%*s使用两个参数--第一个是长度,第二个是要打印的字符串。这里,我告诉它打印一个给定宽度的空字符串,它只打印所需的空格数。
发布于 2013-07-03 17:04:42
只需在格式字符串中添加字段宽度,例如
printf("+--------------+----------\n"
" Postal number| Tele\n"
"----------+-----------------+---------------\n"
"%8u | %3u", number, tele);发布于 2013-07-03 18:20:56
#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;
}https://stackoverflow.com/questions/17443796
复制相似问题