strstr() function
Asked Answered
A

3

6

I am trying to write a program that compares a substring that the user enters with an array of strings.

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

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

int main() {
    char input[10];

    puts("Enter animal name: ");
    fgets(input, sizeof(input), stdin);

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

When I enter frogs, for example it should print the message "frogs are freaky", but it prints out nothing.

So I tried to write a line to print out the value of the strstr() function each time and they all returned 0, which means all the comparisons failed. I don't understand why, can someone help me please?

Abri answered 3/6, 2013 at 20:59 Comment(0)
K
7

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;
}
Knitwear answered 3/6, 2013 at 21:1 Comment(0)
R
5

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

Ramos answered 3/6, 2013 at 21:1 Comment(0)
B
5

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;
Baber answered 3/6, 2013 at 21:1 Comment(1)
*p = 0; == *p = '\0' ??Mezzotint

© 2022 - 2024 — McMap. All rights reserved.