2017-10-10 101 views
0

我正在尝试搜索结构中的元素。所以用户将输入id,如果包含该信息,它将搜索结构以查看它。当我运行程序时,它总是返回数组中的最后一个元素。我不确定我是否正确搜索。这里是我的代码:搜索结构数组中的元素,c编程

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"); 
     } 
    } 
} 
+6

的strcmp将返回0,如果两个字符串是相同的。所以你的if语句不会成立。改为'if(!(strcmp(locationArray [i] .id,locationID))' –

+2

'if(strcmp(locationArray [i] .id,locationID)== 0)''(你也应该添加'break;'at 'if'的结尾停止搜索是否被找到。 –

回答

1

的问题是因为STRCMP返回0时,它匹配:

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"); 
     } 
    } 
}