[英]Searching for a string in a struct
The code below is a code that will track my product costs and remaining quantity.The problem I'm facing with is I can't search the code by下面的代码是跟踪我的产品成本和剩余数量的代码。我面临的问题是我无法通过以下方式搜索代码
if(g[n].name == search[10])
The out put keep showing输出继续显示
"Item not found" “找不到项目”
Im a beginner of c language and was hope to learn more.我是 c 语言的初学者,希望能学到更多。 Please correct my code and send it here so that I can know why my code is wrong.请更正我的代码并将其发送到此处,以便我知道我的代码错误的原因。
#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;
}
}
}
Two bugs:两个错误:
Incorrect use of scanf
:错误使用scanf
:
scanf("%s",&search[10]); --> scanf("%9s", search);
Note: scanf("%9s", &search[0]);
注意: scanf("%9s", &search[0]);
is also fine but the above is the common way.也可以,但以上是常用方法。
Incorrect string compare:不正确的字符串比较:
if(g[n].name == search[10]) --> if(strcmp(g[n].name, search) == 0)
Also notice that you never initialized g[3]
but fn_search
checks it.另请注意,您从未初始化g[3]
但fn_search
检查它。
Then this part:然后这部分:
else
{
printf("\nItem not found.");
break;
}
means that you break the for
loop as soon as an item doesn't match.意味着一旦项目不匹配,您就会中断for
循环。 In other words: Currently you only compare against g[0]
换句话说:目前你只比较g[0]
You don't want that.你不想要那个。 Check all items before printing "Item not found".在打印“未找到项目”之前检查所有项目。
So the for
loop should be more like:所以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.");
Finally:最后:
void fn_search (struct product g[10])
^^
why ??
Either do要么做
void fn_search (struct product g[])
or或者
void fn_search (struct product *g)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.