![](/img/trans.png)
[英]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.