在 C 中,我如何从文件中扫描并与另一个扫描进行比较

In C how do i scan from a file and compare with another scan

为什么我的代码不能正确比较我的字符串,即使我输入与文件中相同的内容,它也不会退出 do 循环。

#include <stdio.h>
#include <string.h>

int main()
{
    char ISBN[100];
    char ISBN1[100];
    char BT [512];
    float BP;
    int dis;
    int quant;

    FILE *fp;

    fp=fopen("bookstore.txt", "r");
    printf("\nEnter the ISBN:");
    scanf("%s", ISBN);
    do
        {
            fscanf(fp,"%[^':']:%[^':']:%f:%d:%d",ISBN1, BT, &BP, &dis, &quant);
        }
    while(strcmp(ISBN, ISBN1) !=0);
    printf("%.2f", BP);
}

这是我的文件包含的数据:

9780273776840:C How to Program:95.90:30:0  
9780131193710:The C Programming Language:102.90:20:30  
9780470108543:Programming fo Dummies:60.20:25:50  
9781118380932:Hacking for Dummies:50.90:78:0  
9781939457318:The 20/20 Diet:80.90:73:10

您可以按如下方式修改循环 -

 if(fp!=NULL){                         // checking success of fopen
while(fscanf(fp," %[^:]:%[^:]:%f:%d:%d",ISBN1, BT, &BP, &dis, &quant)==5){   //check success of fscanf

       if(strcmp(ISBN,ISBN1)==0){     // compare both strins 
               break;                 // if equal break 
          }
      }
 printf("\n%.2f", BP);                // print corresponding value
}

使用 fscanf 作为 while 循环的条件(循环将迭代直到 fscanf 失败)-

while(fscanf(fp," %[^:]:%[^:]:%f:%d:%d",ISBN1, BT, &BP, &dis, &quant)==5)
   /*            ^ don't forget to put this space its intentionally there */

另请注意 fscanf 的格式说明符中所做的更改。

编辑

整个节目-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
     FILE *fp;
     char ISBN[50],ISBN1[50],BT[50];
     int dis,quant;
     float BP;
     fp=fopen("Results.txt","r");
     scanf("%s", ISBN);

     if(fp!=NULL){
        while(fscanf(fp," %[^:]:%[^:]:%f:%d:%d",ISBN1, BT, &BP, &dis, &quant)==5){

            if(strcmp(ISBN,ISBN1)==0) 
                 break;
          }
        printf("\n%.2f", BP);
        fclose(fp);
      }

    return 0;
}

OP 在输入带有空格的标题时肯定有问题,例如 "C How to Program" 只会用 "C".

填充 ISBN

关键问题是scanf()fscanf()使用不当。与其搞乱这种方法,不如使用 fgets() 读取用户输入和文件输入,然后处理读取的数据。

char ISBN[100+2]; // +1 \n [=10=]
printf("\nEnter the ISBN:");
fgets(ISBN, sizeof ISBN, stdin);
ISBN[strcspn(ISBN, "\r\n")] = 0; // lop off end-of-line of line chars

char fileline[700];
while (fgets(fileline, sizeof fileline, fp)) {
  if (sscanf(fileline,"%99[^:]:%511[^:]:%f:%d:%d",ISBN1, BT, &BP, &dis, &quant) == 5) {
    if (strcmp(ISBN, ISBN1) == 0) {
      printf("%.2f", BP);
    }
  }
}