2013-02-24 64 views
0

我怎麼能讓我的功能看起來這樣?編程C - 線路自動編號?

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

我這樣怎麼可以把一個號碼爲每一行,

名字,姓氏和成績?

+2

添加計數器變量,並增加它的'while'環 – 2013-02-24 21:58:01

+0

我試圖內,但不能,也許犯了一個錯誤! – NoWorries 2013-02-24 21:59:51

+0

你嘗試了什麼? – 2013-02-24 22:00:43

回答

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,"."); 

將此代碼詭計循環之前

+0

非常感謝你,它可以與行號一起工作;)你知道如何我可以添加F.Name,L.Name和Grade? – NoWorries 2013-02-24 22:02:37

+0

@HaidoManeen是的查看更新的答案 – 2013-02-24 22:04:51

+0

謝謝@Grijesh Chauhan – NoWorries 2013-02-24 22:10:11

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

謝謝@Jon;) – NoWorries 2013-02-24 22:10:53

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++; 
    } 
+0

非常感謝,現在有用;)@Mohamed KALLEL – NoWorries 2013-02-24 22:05:23