我尝试读取文件然后用它们打印数字行。但我不知道如何在同一时间打印lorem ipsum。因为我对C中的打印功能知之甚少。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
main(){
int c;
int b=1;
//int a[5000]; Shall I use this or any ideas without them?
FILE *xfile;
xfile = fopen("loremipsum.txt", "r");
while((c=getc(xfile)) != EOF){
if(c == '\n'){
printf("%d\n", b); /*STUCK IN THERE... HOW TO PRINT LOREM IPSUM WITH NUMBER LINES?*/
//putchar(a);
b++;
}
}
}
我的lorem ipsum:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae quam non risus consectetur aliquet sed rhoncus purus. Fusce vitae lorem a dui elementum condimentum id id odio. Quisque eu felis eu diam facilisis mollis sit amet id augue. Duis lacinia velit et lorem ullamcorper iaculis. Duis malesuada lacus quis quam congue nec euismod ante condimentum. Donec dignissim augue vitae nulla dapibus vehicula.
我想要的是什么:
1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 2. Donec vitae quam non risus consectetur aliquet sed rhoncus purus. 3. Fusce vitae lorem a dui elementum condimentum id id odio. 4. Quisque eu felis eu diam facilisis mollis sit amet id augue. 5. Duis lacinia velit et lorem ullamcorper iaculis. 6. Duis malesuada lacus quis quam congue nec euismod ante condimentum. 7. Donec dignissim augue vitae nulla dapibus vehicula.
答案 0 :(得分:5)
如果使用fgets
来获取整行而不是一次读取一个字符呢?
char input[256];
int line = 1;
while (fgets(input, sizeof(input), xfile) != NULL)
{
printf("%2d. %s", line++, input);
}
答案 1 :(得分:3)
你有很好的方法,尽管将最后一个字符保存在变量中可能很有用。
int c;
int b = 1;
int prec = '\n';
while ((c = getc (xfile)) != EOF) {
if (prec == '\n')
printf ("%d. ", b++);
putchar (c);
prec = c;
}