格式化输出列表

时间:2014-02-28 04:10:30

标签: c printf

说,我有几行代码输出一些管理员列表(随机场景),他们就像这样

printf("ADMIN LISTT\n\n");
printf("FIRSTNAME        LASTNAME        PASSWORD       AGE       ACOUNT#\n");
printf("\n%s          %s           %s    %d     %d\n",
students.firstname, students.lastname, students.password,
students.age_calculation, students.account_num);

输出会像这样非常丑陋

FIRSTNAME        LASTNAME        PASSWORD       AGE \n");
SAM       WITHER               SAMWITHER123  25     
TEBBY             BOWSER           GIRZZLY145    18

每个字段都没有在正确的主题下正确显示有没有办法让它们更好我不认为有办法让它们精确地在主题下,因为它们是从用户输入放置的,因为每个字符都是输入间距将其他进一步向右推,导致问题(屏幕上的位置全部基于用户输入的字符数量)

2 个答案:

答案 0 :(得分:3)

使用假设学生姓名,姓氏,密码最多40个字符。和年龄和数量最多3位数。

printf("\n%-40s %-40s %-40s %-3s %-3s\n","FIRSTNAME", "LASTNAME","PASSWORD","AGE","ACOUNT");

printf("\n%-40s %-40s %-40s %-3d %-3d\n",students.firstname, students.lastname,students.password, students.age_calculation, students.account_num);

答案 1 :(得分:1)

试试这个...

printf("%14s%14s%14s%5s%8s\n", 
"FIRSTNAME", "LASTNAME", "PASSWORD", "AGE", "ACOUNT#");

printf("%14s%14s%14s%5d%8d\n",
students.firstname, students.lastname, students.password,
students.age_calculation, students.account_num);