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

时间:2015-10-21 13:39:45

标签: c scanf strcmp

为什么我的代码没有正确地比较我的字符串,即使我从文件中输入相同内容,它也不会退出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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

OP肯定在输入带有空格的标题时遇到问题,例如“C如何编程”,这只会ISBN填充"C"

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

char ISBN[100+2]; // +1 \n \0
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);
    }
  }
}
相关问题