0

我正在为图书馆管理系统编写一个程序作为我的 c 项目。我使用 while 循环和!feof条件来检查文件中的book. 因为我读到我们不应该使用它,如果我们必须使用它,我们应该用一些 break 语句来做,而且因为我正在阅读大量的 no。来自文件的变量,我用来found打破while循环。每当Targetandbook.bname将匹配(使用strcmp)时,found设置为 1 并且 while 循环将被终止。这是我在这段代码背后使用的逻辑。这book是一个结构,它book.bname是其中的一部分。我正在为这个程序使用 linux 操作系统。请告诉我我错在哪里?

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

这是我在输入书名后面临无限循环的功能。它进入一个无限循环,打印它遇到的第一本书的名字。我应该怎么办?我的问题与其他类似问题不同,因为我使用两个条件而不是仅 !feof。我使用 a variable作为flag .stillwhile loop没有终止。

4

1 回答 1

0

您没有从文件中读取下一行,因为您根本没有前进。您需要使用fgets从文件fgetc中读取字符串或读取字符。 fgets当它读取一个换行符时会自动停止,因此这可能是一次读取一行的解决方案。如果您使用的是 GNU 版本的 C 库,另一种解决方案是使用 [getLine] ( http://man7.org/linux/man-pages/man3/getdelim.3.html ),它会为您读取一行。

无论您使用什么,您都需要阅读一行,然后移动到下一行,直到到达末尾,这不是您对当前代码所做的事情。

于 2016-11-19T23:46:49.747 回答