[beginner] - question about strstr()

Hi,

I'm trying to learn C.
But i have a problem with using the strstr().

For example
source = "I know your name."
find = "know"

The problem is that I always get this output:
Substring: <null>
instead of
know your name

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void finder(char* source, char* find);


int main(void)
{
    char source[50];
    char find[50];


    printf("Give source:\n");
    fgets(source, sizeof(source), stdin);
    printf("Give search:\n");
    fgets(find, sizeof(find), stdin);


    finder(source,find);
    return EXIT_SUCCESS;
}


void finder(char *source, char *find)
{
    printf("Substring: %s", strstr(source, find));

}


I know the problem lies here: strstr(source, find).

Cause when i use this code everything works like a charm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void finder(char* source, char* find);


int main(void)
{
....
}
void finder(char *source, char *find)
{
    printf("Substring: %s", strstr(source, "know"));

}


Sorry for my bad english.
I hope someone can explain me what I am doing wrong.
Last edited on
Isn't fgets() for file input...?
When you use fgets the newline character at the end of the line is also put into the string. That means find will contain "know\n" that cannot be find inside the string source.
@Peter87: Thank you! I always forget that!
You solved my problem! :)
Topic archived. No new replies allowed.