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