0

I am trying to search for an element in the struct. So the user will enter the id, and it will search the struct to see it if contains that information. When I ran the program, it always returns the last element in the array. I am not sure if I am searching correctly. Here is my code:

typedef struct
{       
    int locationNum;
    char id[15];
    char description[50];
    float latitude;
    float longitude;
} localInfo;


// passing in the locationArray struct and count is the length of the array
void searchLocation(localInfo *locationArray, int count)
{
    char locationID[15];
    printf("\nEnter Location ID to search: ");
    scanf("%s", locationID);
    getchar();

    int i;
    for(i = 0; i < count; i++)
    {
        if(strcmp(locationArray[i].id, locationID))
        {
            printf("Found it!, Here are the informations:\n");
            printf("Location ID: %s\n", locationArray[i].id);
            printf("Location Description: %s\n", locationArray[i].description);
            printf("Location Latitude: %s\n", locationArray[i].latitude);
            printf("Location Longitude: %s\n", locationArray[i].longitude);
        }
        else
        {
            printf("ID is NOT Found\n");
        }
    }
}
2
  • 6
    strcmp will return 0 if two strings are the same. So your if statement will not hold. Change to if(!(strcmp(locationArray[i].id, locationID)) Commented Oct 10, 2017 at 21:50
  • 2
    if (strcmp(locationArray[i].id, locationID) == 0) (you should also add break; at the end of the if to stop searching if it is found. Commented Oct 10, 2017 at 21:51

1 Answer 1

1

The issue is because strcmp return 0 when it matches:

void searchLocation(localInfo *locationArray, int count)
{
    char locationID[15];
    printf("\nEnter Location ID to search: ");
    scanf("%s", locationID);
    getchar();

    int i;
    for(i = 0; i < count; i++)
    {
        if(strcmp(locationArray[i].id, locationID) == 0)
        {
            printf("Found it!, Here are the informations:\n");
            printf("Location ID: %s\n", locationArray[i].id);
            printf("Location Description: %s\n", locationArray[i].description);
            printf("Location Latitude: %s\n", locationArray[i].latitude);
            printf("Location Longitude: %s\n", locationArray[i].longitude);

            break;
        }
        else
        {
            printf("ID is NOT Found\n");
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.