Explosivegamer29
Explosivegamer29

Reputation: 23

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,

The problem is that the for loop stops at the first iteration regardless of there being a match

I have tried using strstr() instead of strcmp() and it works, but since this is a school assignment, i cant use 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)

Expectd output:

Alice 2000
Cooper 2000

Upvotes: 2

Views: 157

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50774

The fscanf format string is wrong, it should be:

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

Note the final \n. Without that, the \n (new line) will not be absorbed and the first item of the next string read will start with \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.

So you need at least this:

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

Upvotes: 3

Related Questions