strcasestr仍然不能正常工作
所以我通读了其他问题,他们被告知在放入任何文件之前先放上#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;
}
的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;
}
为了避免在'char'值为负值时出现未定义的行为,请使用'tolower((unsigned char)needle [j])!= tolower((unsigned char)haystack [i + j]) – chqrlie
@chqrlie感谢您的反馈! C中的约定是为所有参数使用'const char *',并且期望客户端在需要可变结果的情况下转换返回值? – templatetypedef
不,为了与'strstr()'一致以及与OP的用例兼容,参数应该颠倒,原型应该是'char * myStrcasestr(char * haystack,char * needle);'。 'return'语句将需要cast:'return(char *)haystack + i;' – chqrlie
你在Linux上吗? – Barmar
@Barmar不,在窗口上 – Quto
你在使用什么c库? 'Linux'上的'glibc'? – ventiseis