我需要编写一个程序,输出包含匹配字符串“target”的所有行,并将匹配数与总成本相加,
问题在于,无论是否存在匹配,for 循环都会在第一次迭代时停止
我尝试使用 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);
}
文件:
Gem, Alice, 2000
Gold, Bob, 3000
Gem, Cooper, 2000
输入:
3
(文件中的行数)
gem
(目标)
预期输出:
Alice 2000
Cooper 2000
最佳答案
fscanf
格式字符串错误,应该是:
"%[^,], %[^,], %d\n"
注意最后的\n
。否则,\n
(新行)将不会被吸收,并且读取的下一个字符串的第一项将以 \n
开头。
或者更好:使用此格式字符串:
" %[^,], %[^,], %d"
注意开头的空格。使用该格式字符串,所有前导和尾随空格(包括换行符)都将被吸收。
此外,您绝对需要检查 fopen
是否失败,在您的情况下显然没有,但如果由于某种原因无法打开文件,并且您没有进行任何检查,则后续操作f
不会有好结果。
所以你至少需要这个:
...
f = fopen("Customers.txt", "r");
if (f == NULL)
{
printf("Can't open file\n");
return 1;
}
...
关于arrays - strcmp() 函数仅适用于第一次迭代 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70968010/