我想了解fgets的工作原理。为此我写了代码打印" hi"在每行之前,将使用fgets从另一个名为input.txt的文本文件打印。
但它在连续的行之间显示2 hi
而不是1.我无法理解为什么?
我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char singleline[150];//storing each line of input.txt as singleline arrays.
FILE *fp;//file pointer named fp.
fp=fopen("input.txt","r");//reading the text file input.txt
while (!feof(fp)){
fgets(singleline,150,fp);
printf("hi\n");// to check that before each line hi is printed?
puts(singleline);
}
return 0;
}
我的文字文件
rohit sharma,batsman,1,35.0,40.0,2200,20,95
viru,batsman,2,28.0,45.0,1800,02,75
suresh raina,batsman,3,38.0,35.0,2300,15,98
suryaky,batsman,4,30.0,0.0,500,0,10
abd,batsman,5,37.2,0.0,1200,0,50
dhoni,batsman,6,45.2,0.0,2100,0,85
albie,allrounder,7,24.87,27.65,945,80,86
ashwin,bowler,8,8.82,24.37,150,82,85
naraine,bowler,9,6.67,16.94,40,67,49
johnson,bowler,10,12.25,21.33,98,45,33
starc,bowler,11,14.17,28.71,85,14,14
输出
hi
rohit sharma,batsman,1,35.0,40.0,2200,20,95
hi
hi
viru,batsman,2,28.0,45.0,1800,02,75
(till the end)
johnson,bowler,10,12.25,21.33,98,45,33
hi
hi
starc,bowler,11,14.17,28.71,85,14,14
这里有什么错误?
答案 0 :(得分:2)
您发布的内容:
hi
rohit sharma,batsman,1,35.0,40.0,2200,20,95
hi
viru,batsman,2,28.0,45.0,1800,02,75
正如预期的那样,因为你不吃尾随的换行符。您可以在阅读singleline
后添加此行。
if(strlen(singleline) != 0) // because you may have an empty file
singleline[strlen(singleline) - 1] = '\0';
你也可以像alk建议那样做:
singleline[strcspn(singleline, "\n")] = 0;
取自this回答。
while循环的控制语句中的feof()
也会让我重定向到这个问题:Why is while ( !feof (file) ) always wrong?
感谢alk和iharob的有用评论。