2015-12-02 108 views
-1

我遇到了一些我正在編寫的程序的問題。只有當我的子字符串在字符串末尾時,strstr纔有效

  1. 的strstr輸出我的子只有當它在我的字符串的結尾enter image description here
  2. 也輸出後enter image description here
  3. 我已經受夠了「爲const char *大海撈針」問題的一些垃圾字符,然後加入輸入到它,所以我用fgets和的getchar循環做了
  4. 某處它與一個子,這不是隻在年底的工作方式,但後來我輸出字符串和字符串的亞特那
休息

這裏是我的主:

int main() { 
    char haystack[250], 
      needle[20]; 

    int  currentCharacter, 
      i=0; 

    fgets(needle,sizeof(needle),stdin); //getting my substring here (needle) 

    while((currentCharacter=getchar())!=EOF) //getting my string here (haystack) 

    { 
     haystack[i]=currentCharacter; 
     i++; 
    } 

    wordInString(haystack,needle); 

    return(0); 
} 

和我的功能:

int wordInString(const char *str, const char * wd) 
{ 
    char *ret; 
    ret = strstr(str,wd); 

    printf("The substring is: %s\n", ret); 
    return 0; 
} 
+3

有一個終止「\ 0」大海撈針丟失,這將導致你各種各樣的麻煩。 – gnasher729

回答

2

你讀一個字符串fgets()和其他與getchar()高達文件的末尾。在兩個字符串的末尾都有尾隨'\n',因此strstr()只能匹配子字符串(如果它位於主字符串的末尾)。 此外,您不會在haystack的末尾存儲最終的'\0'。您必須這樣做,因爲haystack是本地數組(自動存儲),因此不會隱式初始化。

可以糾正這個問題是這樣的:

//getting my substring here (needle) 
if (!fgets(needle, sizeof(needle), stdin)) { 
    // unexpected EOF, exit 
    exit(1); 
} 
needle[strcspn(needle, "\n")] = '\0'; 

//getting my string here (haystack) 
if (!fgets(haystack, sizeof(haystack), stdin)) { 
    // unexpected EOF, exit 
    exit(1); 
} 
haystack[strcspn(haystack, "\n")] = '\0'; 
+0

1+使用'strcspn()':-) – alk

+0

限制讀循環不會溢出'haystack'也會很好...... ;-) – alk

+0

我看到它了,我完全同意針,因爲我希望它僅限於1行,但當談到乾草堆 - 我希望它超過1行。考慮到這一點,我可以以某種方式做到這一點,所以我不需要定義乾草堆一個[250]元素數組,它會計數元素,因爲我結束輸入?但是接下來會出現另一個問題,因爲我不會在我的針頭裏有這個問題,但是我可以在乾草堆裏找到它 - 如果在我的草垛中將針頭分成兩行,它就不會匹配。 – NoobProgrammerWannabe