2015-10-13 70 views
0

我放出来应该是这样的如何打印在打印到控制台的各行的开始,打印文件的行号

1)你好...
2)编程1 ...
3)学生!
4)欢迎使用File I/O!

我已经做了一切,但我无法弄清楚如何打印每行的数字?

到目前为止我得到

#include <stido.h> 

int main(int argc,char* argv[]) 
{ 

    char string[200]; 
    FILE* file = fopen("file2.txt","r"); 
    while(fscanf(file, "%c", string) ==1) 
    { 
     printf("%c", *string); 
    } 

    fclose(file); 
    return 0; 
} 
+0

看起来你会想创建一个临时变量。在while循环的每个循环中增加temp变量。 int lineNum = 1; while ...(sprintf(str,“%d”,linNum); printf(“%c”,* string);}沿着这些行的东西。 – Enkode

回答

0
int num = 1; 
char line[200]; 
FILE* file = fopen("file2.txt","r"); 
while(fgets(line, 200, file)) 
{ 
    printf("%d) %s", num, line); 
    num++; 
} 
0

为避免线路长度的限制等char string[200],简单通过如果珍贵char检查检测行的开始是一个换行,然后打印的数量。在线数量不需要保守,所以使用宽类型。

#include <assert.h> 
#include <stido.h> 

int main(int argc,char* argv[]) { 
    int previous = '\n'; 
    int ch; 
    unsigned long long line_count = 0; 
    FILE* file = fopen("file2.txt","r"); 
    assert(file); 
    while((ch = fgetc(file)) != EOF) { 
     if (previous == '\n') { 
     printf("%llu) ", ++line_count); 
     } 
     fputc(ch, stdout); 
     previous = ch; 
    } 
    fclose(file); 
    return 0; 
}