C 只有当我的子字符串位于字符串的末尾时,strstrstr才起作用

C 只有当我的子字符串位于字符串的末尾时,strstrstr才起作用,c,strstr,C,Strstr,我现在写的程序遇到了几个问题 strstr仅当子字符串位于字符串末尾时才输出它 之后它还会输出一些垃圾字符 我在“constchar*haystack”中遇到了问题,然后向其中添加了输入,所以我使用fgets和getchar循环进行了处理 在这个过程中的某个地方,它使用的子字符串不仅在末尾,而且我还输出了子字符串和其他字符串 以下是我的主要观点: int main() { char haystack[250], needle[20]; int

我现在写的程序遇到了几个问题

  • strstr仅当子字符串位于字符串末尾时才输出它
  • 之后它还会输出一些垃圾字符
  • 我在“constchar*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'
    ,因此
    strstrstr()
    只能与位于主字符串末尾的子字符串匹配。 此外,您不会将最后一个
    '\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';
    

    haystack中缺少一个终止'\0',这将给您带来各种各样的麻烦。1+使用
    strcspn()
    :-)限制读取循环不溢出
    haystack
    ,也会很好…;-)我明白了,我完全同意针的说法,因为我只想把它限制在一行以内,但说到干草堆,我希望它不止一行。考虑到这一点,我是否可以这样做,这样我就不需要定义haystack一个[250]元素数组,它会在我结束输入时对元素进行计数?但随后会出现另一个问题,因为我的针中没有\n,但我会将它放在haystack中-因此,如果针在我的haystack中被分成两行,它将不匹配。当您将其余的stdin读入haystack缓冲区时,您可以将行转换为空格。