制表符确实有一席之地,但太僵化,无法用于对齐可变长度数据项进入恒定宽度列。printf()
- sprintf()
格式填充、宽度说明符、左对齐和右对齐技术对于您想要执行的操作都很有用。底部有一个参考链接,描述了这些方法和其他方法的详细信息。
设计桌子时要考虑的事项:
- 可用的总字段宽度是多少(所有列共享的宽度)
- 每列允许的最大字段宽度是多少
- 格式化应确保写入列的数据不超过其列的宽度(截断字符串、在数字中使用较少的有效数字等)
- 在格式说明符中使用灵活的格式化技术,例如填充、对齐等,以满足预期的数据宽度要求。 (参见下面的示例。)
以下代码提供了使用这些技术的一些示例:
printf("|%-10d|, |%10d|\n", 1, 2);//left and right justtification within field
int pad1 = 5;
int pad2 = 10;
printf("|%.*d|, |%.*d|\n", pad1, 1, pad2, 2);//"*", variable padding within field
printf("|%-15s|\n", "string");// - left justifies
printf("|%15s|\n", "another string");// - right justifies
char *pad = " "; //10 spaces
printf("|%s%*s|\n", pad, -9, "string");//combination of padding and justification
给定以下参数假设:
typedef enum {
Student,
Bartender
}enum_e;
typedef struct {
int processid;
int threadid;
int t_state;
enum_e p_type;
int light_beer_required;
int light_beer_consumed;
int wake_count;
int turnaround_time;
} pcb_s;
pcb_s pcb[3] = { {1234, 3, 1, Student, 1, 1, 2, 12},
{2345, 2, 2, Bartender, 1, 1, 2, 12},
{3456, 1, 3, Student, 1, 1, 2, 12} };
...以下是您的代码,经过修改以仅使用其中一种技术:
for (int i = 0; i < size; i++)
{
// printf("|%d\t\t| %d\t\t| %d\t\t\t| %d\t\t\t| \
%d\t\t\t| %d\t\t\t| %d\t\t\t\t|%s\t\t| \
%d\t\t\t| %d\t\t| %d\t\t| %d\t\t|\n",
printf("|%10d|%3d|%3d|%3d|%3d|%3d|%3d|%15s|%3d|%3d|%3d|%d|\n",
pcb[i].processid, pcb[i].threadid,
(pcb[i].t_state == 1)?1:0,
(pcb[i].t_state == 2)?1:0,
(pcb[i].t_state == 3)?1:0,
(pcb[i].t_state == 4)?1:0,
(pcb[i].t_state == 5)?1:0,
(pcb[i].p_type == Student)?"Student": "Bartender",
pcb[i].light_beer_required,
pcb[i].light_beer_consumed,
pcb[i].wake_count,
pcb[i].turnaround_time);
}
output of above:
这是一个资源其中详细介绍了这些以及许多其他格式化技术。