strstr works only if my substring is at the end of string

对着背影说爱祢 提交于 2020-01-11 14:46:46

问题


I've encountered a couple of problems with the program that i'm writing now.

  1. strstr outputs my substring only if it's at the end of my string

  2. it also outputs some trash characters after that

  3. I've had problems with "const char *haystack" and then adding input to it, so i did it with fgets and getchar loop
  4. somewhere along the way it worked with a substring that was not only at the end, but then i outputted substring and the rest of the string ater that

here is my main:

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);
}

and my function:

int wordInString(const char *str, const char * wd)
{
    char *ret;
    ret = strstr(str,wd);

    printf("The substring is: %s\n", ret);
    return 0;
}

回答1:


You read one string with fgets() and the other with getchar() upto the end of file. There is a trailing '\n' at the end of both strings, Hence strstr() can only match the substring if it is at the end of the main string. Furthermore, you do not store a final '\0' at the end of haystack. You must do this because haystack is a local array (automatic storage), and as such is not initialized implicitly.

You can correct the problem this way:

//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';


来源:https://stackoverflow.com/questions/34048907/strstr-works-only-if-my-substring-is-at-the-end-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!