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

后端 未结 1 741
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 15:33

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
相关标签:
1条回答
  • 2021-01-26 15:44

    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';
    
    0 讨论(0)
提交回复
热议问题