2017-02-20 143 views
3

所以我通讀了其他問題,他們被告知在放入任何文件之前先放上#define _GNU_SOURCE,它會起作用,但它對我不起作用。我也嘗試加入#define _GNU_SOURCE char *strcasestr(const char *haystack, const char *needle);,但仍然無法正常工作。我找不到任何其他的東西,也許任何人都可以幫忙?提前致謝。strcasestr仍然不能正常工作

錯誤:函數「strcasestr」

/** 
* 
* Description: This is code for Lab 3 Task 2. 
*    Reads data from file and gives opportunity to search by cities 
*/ 
#define _GNU_SOURCE 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

    printf("Please input the city you want to find employees in:"); 
    scanf("%s", input); 
    maxline = i; 
    for (i = 0; i <= maxline; i++) { 
     if (strcasestr(employee[i].city, input) != 0) { // PROBLEM 
      printf("%d %s %s %s\n", &employee[i].ID, employee[i].fn, 
            employee[i].ln, employee[i].city); 
      amount++; 
     } 
    } 
    printf("%d matches out of %d members", amount, maxline); 
    return 0; 
} 
+1

你在Linux上嗎? – Barmar

+0

@Barmar不,在窗口上 – Quto

+0

你在使用什麼c庫? 'Linux'上的'glibc'? – ventiseis

回答

2

strcasestr功能的隱式聲明不能作爲標準的Windows的一部分,建立環境。它不是C標準庫的一部分,只附帶某些平臺和構建環境。

但是,您可以編寫自己的版本。這是一個基於天真字符串匹配算法的簡單程序。使用Rabin-Karp,Boyer-Moore或Knuth-Morris-Pratt算法可以做得更好:

char* myStrcasestr(const char* haystack, const char* needle) { 
    /* Edge case: The empty string is a substring of everything. */ 
    if (!needle[0]) return (char*) haystack; 

    /* Loop over all possible start positions. */ 
    for (size_t i = 0; haystack[i]; i++) { 
     bool matches = true; 
     /* See if the string matches here. */ 
     for (size_t j = 0; needle[j]; j++) { 
      /* If we're out of room in the haystack, give up. */ 
      if (!haystack[i + j]) return NULL; 

      /* If there's a character mismatch, the needle doesn't fit here. */ 
      if (tolower((unsigned char)needle[j]) != 
       tolower((unsigned char)haystack[i + j])) { 
       matches = false; 
       break; 
      } 
     } 
     if (matches) return (char *)(haystack + i); 
    } 
    return NULL; 
} 
+2

爲了避免在'char'值爲負值時出現未定義的行爲,請使用'tolower((unsigned char)needle [j])!= tolower((unsigned char)haystack [i + j]) – chqrlie

+0

@chqrlie感謝您的反饋! C中的約定是爲所有參數使用'const char *',並且期望客戶端在需要可變結果的情況下轉換返回值? – templatetypedef

+0

不,爲了與'strstr()'一致以及與OP的用例兼容,參數應該顛倒,原型應該是'char * myStrcasestr(char * haystack,char * needle);'。 'return'語句將需要cast:'return(char *)haystack + i;' – chqrlie