2016-10-03 71 views
1

我想搜索是否有任何曲目可用的曲目數組。當我總是給出任何輸入strstr()函數返回false。如果我使用else塊,則每次其他塊都正在執行。。當我通過任何輸入總是功能返回false

char tracks[][80] = { 
    "I left my heart in Harvard Med School", 
    "Newark, Newark - a wonderful town", 
    "Dancing with a Dork", 
    "From here to maternity", 
    "The girl from Iwo Jima", 
    }; 

    // function to search the track with entered search string // 
    void find_track(char search_for[]) { 
     int i; 
     for (i = 0; i < 5; i++) { 
      /** this if condition is returning false every time */ 
      if (strstr(tracks[i], search_for)){ 
      printf("Track %i: '%s'\n", i, tracks[i]); 
      }/**else{ 
       printf("some thing went wrong @ %i\n", i); 
      }**/ 
     } 
    } 



    int main() { 
     char search_for[80]; 
     printf("Search for: "); 
     fgets(search_for, 80, stdin); 
     find_track(search_for); 
     return 0; 
    } 

輸入:

gcc test.c -o test && test 

搜索:with

預期的結果:Track 2:'Dancing with a Dork'

請幫助我。

+0

單步與您的調試器。 – KevinDTimm

+4

[從fgets中刪除換行符](https://stackoverflow.com/questions/2693776)。 – user3386109

回答

2

fgets也讀取換行符。您需要將其從search_for中刪除,然後將其傳遞到​​。

請參閱Removing the newline from fgets

+2

去與優雅的獎金答案,而不是醜陋的接受的答案 –

+0

我看到多種方式來實現這一目標,但「search_for [len-1] ='\ 0;」之間的區別是什麼?和「search_for [strcspn(search_for,」\ n「)] = 0;」。哪個更好用,爲什麼? – Nara

+0

@Nara,我認爲'search_for [strcspn(search_for,「\ n」)] = 0;'因爲它沒有假設發現換行符的位置,所以更好。 –