strstr() function

笑着哭i 提交于 2019-12-05 06:02:40

This is because your string contains the newline character.

From the fgets documentation:

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

This should fix the problem (demo):

#include <stdio.h>
#include <string.h>

char animals[][20] = {
"dogs are cool",
"frogs are freaky",
"monkeys are crazy"
};

int main() {
    char input[10];

    printf("Enter animal name: ");
    scanf("%9s", input);

    int i;
    for(i = 0; i < 3; i++) {
        if(strstr(animals[i], input))
            printf("%s", animals[i]);
    }
    return 0;
}

fgets includes the input newline character in the buffer. Your strings don't have a newline in them, so they'll never match.

Most likely, fgets() includes the newline character that is entered when the user presses Enter. Remove it:

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