我现在编写的程序遇到了一些问题。
- strstr outputs my substring only if it's at the end of my string
- it also outputs some trash characters after that
- 我遇到了“const char *haystack”的问题,然后向其中添加输入,所以我使用 fgets 和 getchar 循环来完成它
- 在此过程中的某个地方,它使用的子字符串不仅位于末尾,而且随后我输出了子字符串,然后输出了字符串的其余部分
这是我的主要内容:
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()
仅当子字符串位于主字符串末尾时才能匹配。
此外,您不存储最终的'\0'
在......的最后haystack
。你必须这样做,因为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';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)