[英]Function strstr only detects the substring in the last line of the text file?
[英]strstr works only if my substring is at the end of string
我现在编写的程序遇到了两个问题。
这是我的主要内容:
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;
}
您可以使用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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.