2017-10-07 25 views
0

我編輯了這個問題,因爲解決方案沒有按照我的意圖工作。是否有可能編寫某種if語句或任何其他代碼,當輸入的字符串不存在於該struct數組中時,打印出錯誤消息?打印出錯誤信息後,它再次詢問字符串。我已經嘗試了一段時間,似乎無法做到正確。在結構數組中搜索字符串

int ordet=0; char_sokafras[20]; 
printf("Name?\n"); 
scanf("%s", soka_fras); 
while(ordet<*num_items) 
{ 
if(strstr(varor[ordet].name, soka_fras)) 
{ 
printf("Name found!\n"); 
soka[hitta_tecken]=varor[ordet]; 
hitta_tecken+=1; 
} 
ordet+=1; 
} 
+1

你讀過[文件](http://man7.org/linux/man-pages/man3/strstr.3。 HTML)? – alk

+0

這個問題還不清楚。例如,你想讓代碼提示輸入另一個字符串嗎? – user3629249

回答

1

strstr返回指向在草堆子串的開始。從手冊頁:

如果needle爲空字符串,則返回haystack;如果針在乾草堆中無處可尋,則返回NULL;否則返回指向第一次出現針的第一個字符的指針。

修訂while循環,這應該是足夠了:

while (strstr(varor[i].name, soka_fras) != NULL) 
+0

@ M.M固定(需要更多字符) – Carey