Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strstr not functioning

Why does this particular piece of code return false on the strstr() if I input "test"?

char input[100];

int main()
{
    fgets(input, 100, stdin);
    printf("%s", input);

    if(strstr("test message", input))
    {
        printf("strstr true");

    }


}

I thought strstr searched the first param for instances of the second param? It works when I replace input with some text or just assign it something directly, but it seems to not work with fgets.

like image 660
KWJ2104 Avatar asked Oct 30 '11 02:10

KWJ2104


People also ask

What does Strstr return if failed?

The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL.

What is Strstr function in C++?

strstr() in C/C++ In C++, std::strstr() is a predefined function used for string handling. string. h is the header file required for string functions. This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-string s2 in the string s1.

Why Strstr function is used?

The strstr() Function It is used to search whether a substring is present in the main string or not. It returns pointer to first occurrence of s2 in s1.

What type of function is Strstr?

strstr is a C standard library string function as defined in string. h. strstr() has the function signature char * strstr(const char *haystack, const char *needle); which returns a pointer to a character at the first index where needle is in haystack, or NULL if not present.


2 Answers

It's because fgets stores the newline character so when strstr does a comparison it fails.

From the man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

like image 137
sashang Avatar answered Sep 28 '22 00:09

sashang


Add input[strlen(input) - 1] = '\0'; after the fgets. fgets reads in the newline char ('\n'). There is no '\n' in "test message" so input will never be contained within it.

You should really check to see if the newline is at the end of the buffer after calling fgets to know if the whole line was able to actually fit into it, and also to obviously remove it.

like image 33
AusCBloke Avatar answered Sep 28 '22 00:09

AusCBloke