2013-07-30 90 views
0

我不知道這是不是最好的解決辦法,但是這是我經過長時間的搜尋後發現:搜索通過結構數組

我想在MyString數組內搜索,如果它的發現讓我看看這個國家。這是我到目前爲止,但使用結構數組是有點複雜,這樣做我懇請您的幫助

char *mystring = "butter"; 

typedef struct user_data { 
char* company; 
char* country; 
}user_data; 


user_data comp[]={ 
    { .company = "Company selling Eggs", .country = "United Kingdom" }, 
    { .company = "Company selling Butter", .country = "United States" }, 
    ..................... //other structures (around 200) 
}; 

如何使用STRCMP與?

+1

一個循環?使用'sizeof(comp)/ sizeof(comp [0])'獲取數組中的條目數量。 –

+0

http://linux.die.net/man/3/strcmp – Jeyaram

+1

@ShaMora是循環的問題或strcmp(item.company,mystring)? – doctorlove

回答

3

你必須使用strstr()而不是strcmp()

int i; 
for (i=0; i<sizeof(comp)/sizeof(comp[0]); i++) { 
    if (strstr(comp[i].company, mystring)) 
     printf("Country is: %s\n", comp[i].country) 
} 
+0

謝謝!有效 – ShaMora