Reputation: 87
I need to write a programm where two strings are entered through the keyboard and the 1st string is searched for the 2nd and then the point where it first appeared is given out.
#include <stdio.h>
#include <string.h>
int main() {
char in1[10000];
char in2[10000];
fgets(in1, sizeof(in1), stdin);
fgets(in2, sizeof(in2), stdin);
printf("%d", strstr(in1, in2) - in1+1);
return 0;
}
I did 3 tests
in1=11121
in2=121
result=3 correct
in1=11121121
in2=121
result=6 wrong
in1=11121211
in2=121
result=-2348863 obviously wrong
in1=111211211211
in2=121
result=-2348879
I don't know why it gives out the 2nd time the sequence occurs if it occurs twice and a big negative number if it occurs thrice.
What did I do wrong?
Upvotes: 2
Views: 107
Reputation: 5543
The problem is, that you don't discard the newline characters. So, what you really searched for in your first input example was "121\n"
and this matches the end of "11121\n"
. And the first match of "121\n"
in "11121121\n"
is at 6-th position.
What happens with "11121211\n
" and "121\n"
is: There is no match and strstr
returns 0.
int main() {
char in1[10000];
char in2[10000];
fgets(in1, sizeof(in1), stdin);
{ /* Delete the newline character if there is one. */
size_t len = strlen(in1);
if(in1[len-1]=='\n') in1[len-1] = 0;
}
fgets(in2, sizeof(in2), stdin);
{
size_t len = strlen(in2);
if(in2[len-1]=='\n') in2[len-1] = 0;
}
char *match = strstr(in1, in2);
if(match) {
printf("%td\n", match-in1+1);
// t is the conversion specifier for ptrdiff_t
}
return 0;
}
Also, don't forget to check the return values of fgets
. Also note, that len-1
is an invalid offset in case len
is 0. So you must handle this either.
Upvotes: -1
Reputation: 1
because function: char *fgets(char *buf, int bufsize, FILE *stream)
will get the '\n'
;
so in your case,your 2nd test is "11121121'\n'\0\"
and "121'\n''0'",
you can use "debug" to see the values of in1
and in2
Upvotes: 0
Reputation: 126
In this kind of situation it's better to use scanf
because it truncates newlines from input while fgets
does not. Also, you should use %ld
since you're doing an operation with pointers (or make a cast to int
).
The code below works for all your examples:
#include <stdio.h>
#include <string.h>
int main()
{
char in1[10000];
char in2[10000];
int i;
scanf("%s", in1);
scanf("%s", in2);
char* result = strstr(in1, in2);
if (result != NULL) printf("%ld\n", strstr(in1, in2) - in1 + 1);
else printf("No match\n");
return 0;
}
Upvotes: 2