我怎么能让我的功能看起来那样?
F.Name L.Name Grade
...... ...... .....
1)Martin Peter 7
2)Rani Sari 9
3)Kara Sandler 4
4)Charlie Adam 5
我的功能看起来像这样 :
Martin Peter 7
Rani Sari 9
Kara Sandler 4
Charlie Adam 5
C代码看起来像这样
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char f[500];
char set;
char line[100];
FILE *filename;
printf("Name of file?: ");
scanf("%s", f);
filename = fopen(f, "r");
if((filename == NULL)){
printf("error!\n");
return;
}
else (
printf("\n")
);
while ( fgets (line , sizeof line, filename) != NULL )
{
fputs (line, stdout );
}
}
那么如何为每一行添加一个数字
名字,姓氏和成绩?
答案 0 :(得分:2)
你可以这样做:
i=1;
while ( fgets (line , sizeof line, filename) != NULL )
{
printf("%3d)",i);
fputs (line, stdout );
i++;
}
实际上如果你关心输出格式,你应该使用printf
函数。
printf("%-15s %-15s %-15s\n","F.Name","L.Name", "Grade");
printf("%*s %*s %*s",5,".",5,".",5,".");
在wile循环之前放置此代码
答案 1 :(得分:1)
保留一个为每一行增加的计数器:
// int line_num = 0 has been declared at the top
while ( fgets (line , sizeof line, filename) != NULL )
{
printf("%3d) %s\n", ++line_num, line);
}
答案 2 :(得分:1)
int i = 1;
printf(" F.Name L.Name Grade\n");
printf(" ...... ...... .....\n");
while ( fgets (line , sizeof line, filename) != NULL )
{
printf("%d)");
fputs (line, stdout );
i++;
}