Jan 19, 2012 at 9:55pm UTC
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 Jan 19, 2012 at 9:58pm UTC
Jan 19, 2012 at 10:06pm UTC
Isn't fgets() for file input...?
Jan 19, 2012 at 10:10pm UTC
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.
Jan 19, 2012 at 10:14pm UTC
@Peter87: Thank you! I always forget that!
You solved my problem! :)