问题
I am coding a program for a library management system as my project in c. I used a while loop along with !feof
condition to check the file for book
. Since I read that we should not use it, and if we must, we should do it with some break statement and also since I was reading large no. of variables from file, I used found
for breaking the while loop. whenever the Target
and book.bname
will match (using strcmp
), found
is set to 1 and while loop will be terminated. This is the logic I used behind this code. Here book
is a structure of which book.bname
is a part. I am using linux os for this program. Please tell me where I am mistaking?
void Searchbook()
{
int i;
char Target[25],stats[3];
int Found=0;
if((librecord=fopen("librecord.txt","r"))==NULL)
printf(" ! The File is Empty...\n\n");
else
{
printf("\nEnter The Name Of Book : ");
scanf("%s",Target);
while(!feof(librecord)&& Found==0)
{
fscanf(librecord,"%d %s %s %d %d",&book.bid,book.bname,book.author,&book.status,&book.nooftitles);
if(strcmp(Target,book.bname)==0)
Found=1;
for(i=0;i<book.nooftitles;i++)
fscanf(librecord,"%s",book.titles);
}
if(Found)
{
if(book.status==IN)
strcpy(stats,"IN");
else
strcpy(stats,"OUT");
printf("\nThe Unique ID of The Book: %d\nThe Name of Book is: %s\nThe Author is: %s\nThe Book Status:%s\n\n",book.bid,book.bname,book.author,stats);
}
else if(!Found)
printf("! There is no such Entry...\n");
fclose(librecord);
}
}
This is a function in which I am facing the infinite loop after entering the name of the book. It goes into an infinite loop printing the name of first book it encounters. What should i do? my problem is different than the other similar question since i am using two conditions instead of only !feof
. I am using a variable
as a flag
.still the while loop
is not terminating.
回答1:
You are not reading the next line from the file as you are not advancing at all.
You need to use fgets
to read a string from the file or fgetc
to read a char.
fgets
stops automatically when it reads a new line character so that could be a solution to read one line at a time.
Another solution if you are using the GNU version of the C library is to use [getLine] (http://man7.org/linux/man-pages/man3/getdelim.3.html) which reads a line for you.
Whatever you use, you need to read a line and then move to the next line until the end is reached, which is not what you are doing with your current code.
来源:https://stackoverflow.com/questions/40697487/using-whilefeof-with-terminating-condition-still-it-is-going-in-infinite-loo