下面的代码是跟踪我的产品成本和剩余数量的代码。我面临的问题是我无法通过
搜索代码if(g[n].name == search[10])
输出不断显示
<块引用>“未找到项目”
我是c语言的初学者,希望能学到更多。请更正我的代码并将其发送到这里,以便我知道为什么我的代码是错误的。
#include <stdio.h>
struct product
{
char name[10];
int quantity;
float costs;
};
void fn_search (struct product g[]);
int main ()
{
int n;
struct product g[4];
strcpy(g[0].name,"aa1");
g[0].quantity = 10;
g[0].costs = 1;
strcpy(g[1].name,"bb2");
g[1].quantity = 10;
g[1].costs = 2;
strcpy(g[2].name,"bb3");
g[2].quantity = 10;
g[2].costs = 3;
fn_search (g);
}
void fn_search (struct product g[10])
{
int n;
char search[10];
printf("Search>> ");
scanf("%s",&search[10]);
for (n=0;n<4;n++)
{
if(g[n].name == search[10])
{
printf ("\ncosts = NTD%.2f",g[n].costs);
printf ("\nquantity = %d\n",g[n].quantity);
}
else
{
printf("\nItem not found.");
break;
}
}
}
答案 0 :(得分:4)
两个错误:
scanf
的错误使用:
scanf("%s",&search[10]); --> scanf("%9s", search);
注意:scanf("%9s", &search[0]);
也可以,但以上是常用方法。
不正确的字符串比较:
if(g[n].name == search[10]) --> if(strcmp(g[n].name, search) == 0)
另请注意,您从未初始化 g[3]
,但 fn_search
会检查它。
那么这部分:
else
{
printf("\nItem not found.");
break;
}
表示一旦项目不匹配就中断 for
循环。换句话说:目前您只与 g[0]
你不想那样!在打印“找不到项目”之前检查所有项目。
所以 for
循环应该更像是:
for (n=0;n<4;n++)
{
if(strcmp(g[n].name, search) == 0)
{
printf ("\ncosts = NTD%.2f",g[n].costs);
printf ("\nquantity = %d\n",g[n].quantity);
return; // Exit function when match is found
}
}
// When execution arrives here, there was no matching element
printf("\nItem not found.");
最后:
void fn_search (struct product g[10])
^^
why ??
要么做
void fn_search (struct product g[])
或
void fn_search (struct product *g)