0

我怎样才能让我的功能看起来那样?

  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 );
        } 
}

那么我怎样才能为每一行输入一个数字,

名字、姓氏和年级?

4

3 回答 3

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 循环之前

于 2013-02-24T21:59:33.860 回答
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);
} 
于 2013-02-24T21:59:05.010 回答
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++;
    } 
于 2013-02-24T22:00:06.060 回答