In my register, I want to find all the words that match user input and display them.
For example if I have words like redapple, rottenapple, apple, banana in my register.
And user inputs apple I want to be able to dispaly redapple, rottenapple, apple and their itemnumber and inventory balance. I cannot display in the right way and cannot figure it why, have tried different way and I will post my last try. Thank you!
void search(Car a[],int nr){
char ItmName[50];
int i;
while(1){
printf("Type item name (q for menu): ");
scanf("%s%*c", &ItmName);
if(strcmp(ItmName,"q")==0){
return;
}else{
for(i=0;i<nr;i++){
char *word = strstr(a[i].name,ItmName);
for(i=0;i<nr;i++)
if(word==itemN){
printf("%d\t\t%s\t\t%d\n", a[i].itemNmr, a[i].name, a[i].inventory);
}
return;
}
}
}
}
Your nested loop use the same control variable,
i, and continuation condition, which ensures only one iteration of the outer loop occurs.The contents of the loop make little sense. You repeatedly compare a pointer to the first element of the input buffer (
itemN; pressumablyitemName) against the pointer value returned bystrstr, after it looks through the name field of only the first element of theaarray for the substring provided initemName.Rewritten verbosely, this reads as
which hopefully you can see makes no sense. A pointer value that points to an element of
a[0].namewill never be equal to the pointer value that points to the first element ofitemName- as that would require their memory to overlap somehow.In any case, this should not require any nested loops, as this can be done with a linear search of your array of structures.
First suggestion: move the user input to outside the function. Make
searchaccept a third argument, a string to search for in each structures name. Separately (and repeatedly) take user input and then call this function.Second suggestion: forget
scanfexists entirely. Usefgets(andsscanfif you need to extract formatted data from the string).Here's a cursory example of a linear search function: