-
Search
Help me please:
Let's say I have this struct
Code:
struct Cars {
char brand[30];
char model[30];
char serial_number[30];
} car[30];
I add the number of cars that i want...(...)
After, i want to make a search by brand, let's say I want to search for all the Ferrari cars that I added and I want that appear in the search all the model and serial numbers of the Ferraris that I've searched.
If there is not any car of the brand that I've searched I wan't that appear on the screen "car not found" or something like that.
I tried a couple of things but i still don't know how to do this kind of things.
I can't use pointers.
PS:I invented this example right now.
-
Code:
for(i = 0;i < num_cars;++i)
if(!strcmp(car[i].brand, "Ferrari"))
{
// Show details for this car
}
-
Very similar to searching through an array of strings, but in this case, you need to bring the specific struct member name, into it:
Code:
struct Cars {
char brand[30];
char model[30];
char serial_number[30];
} car[30];
for(i=0;i<numOfCars;i++) {
if((strcmp(car[i].brand, "Ford"))==0)
printf("Ford: %s %s\n",car[i].model, car[i].serial_number);
}
Comparisons will be case sensitive, of course.
-
that "Ferrari" that i said was an example.
I have to input the name that i want to search.
i tried this before but didn't worked
Code:
printf("\nBrand: ");
scanf("%s",search);
for(j=0;j<i;j++)
{
if(strcmp(search,car[j].brand)==0)
{
//car details
}
-
You need TWO strings in your call to strcmp(). Naturally, the name of the string is also a pointer to the base of the string, but pointers are everywhere in your system anyway, under the hood.
Code:
if((strcmp(car[i].brand, "Ford"))==0) //car[i].brand AND "Ford" are the two strings in my example.
//your call to strcmp() needs two strings, not one.
-
Well the problem wasn't in this piece of code...i had the j(number of cars) declared at 0 and that was why the programm didn't run because it was assuming that there were no cars.
Stupid mistake
Thank you to all of you :)