简体   繁体   English

strcmp() function 仅适用于第一次迭代 C

[英]strcmp() function only works on first iteration C

I need to make a program that outputs all lines that contain a matching string "target" and sum up the number of matches along with the total cost,我需要制作一个程序,输出包含匹配字符串“target”的所有行,并将匹配数与总成本相加,

The problem is that the for loop stops at the first iteration regardless of there being a match问题是 for 循环在第一次迭代时停止,无论是否存在匹配项

I have tried using strstr() instead of strcmp() and it works, but since this is a school assignment, i cant use strstr()我尝试使用 strstr() 代替 strcmp() 并且它有效,但由于这是学校作业,我不能使用 strstr()

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

struct data{
    
    char product[100];
    char name[100];
    int price;

};

int main(){

    FILE *f;
    
    f = fopen("Customers.txt", "r");
    int x;
    
    
    scanf("%d",&x);
    
    struct data arr[x];
    
    for(int i=0;i<x;i++){
        fscanf(f,"%[^,], %[^,], %d",arr[i].product,arr[i].name,&arr[i].price);
    }
    
    char target[100];
    int res;
    int count=0;
    int total=0;
    
    scanf("%s",target); 

    for(int j=0;j<x;j++){
        
        res=strcmp(arr[j].product,target);
        
        if(res==0){
            printf("%s, %s, %d",arr[j].product,arr[j].name,arr[j].price);
            count++;
            total = total + arr[j].price;
        }
        else{
            continue;
        }
    }
    printf("\nTotal Buyers: %d\n",count);
    printf("Total Amount: %d\n",total);

}

File:文件:

Gem, Alice, 2000
Gold, Bob, 3000
Gem, Cooper, 2000

Input: 3 (No. of lines in the file) Gem (target)输入: 3 (文件中的行数) Gem (目标)

Expectd output:预期 output:

Alice 2000
Cooper 2000

The fscanf format string is wrong, it should be: fscanf格式字符串错误,应该是:

"%[^,], %[^,], %d\n"

Note the final \n .注意最后的\n Without that, the \n (new line) will not be absorbed and the first item of the next string read will start with \n .没有它, \n (新行)将不会被吸收,并且下一个读取的字符串的第一项将以\n开头。

Or even better: use this format string:甚至更好:使用此格式字符串:

" %[^,], %[^,], %d"

Note the space at the beginning.注意开头的空格。 With that format string all leading and trailing whitespace, including the newline, will be absorbed.使用该格式字符串,所有前导和尾随空格(包括换行符)都将被吸收。

Furthermore you absolutely need to check if fopen fails, in your case it apparently doesn't, but if the file cannot be opened for some reason, and you do not any checks, the subsequent operations on f wont end well.此外,您绝对需要检查fopen是否失败,在您的情况下显然没有,但是如果由于某种原因无法打开文件,并且您没有进行任何检查,则f的后续操作将不会很好地结束。

So you need at least this:所以你至少需要这个:

...
f = fopen("Customers.txt", "r");
if (f == NULL)
{
  printf("Can't open file\n");
  return 1;
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM