I'm working through an example of using the strstr()
function.
If I input "Pamela Sue Smith", why does the program output ""Pamela" is a sub-string!" and not ""Pamela Sue Smith" is a sub-string!".
#include <stdio.h>
#include <string.h>
void main(void)
{
char str[72];
char target[] = "Pamela Sue Smith";
printf("Enter your string: ");
scanf("%s", str);
if (strstr( target, str) != NULL )
printf(" %s is a sub-string!\n", str);
}
main
does not have return-type void
but int
. scanf
can fail. Check the return-value. %s
only reads non-whitespace, until the next whitespace (thus 1 word). %s
does not limit how many non-whitespace characters are read. A buffer-overflow can be deadly. %71s
(buffer-size: string-length + 1 for the terminator) strstr
. From the manual page for scanf
:
“s” — Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
So, the part “Sue Smith” never makes it to str
. You could use fgets
which allows you to read a whole line at a time:
if (fgets(str, sizeof str, stdin) == NULL) {
printf("End of file\n");
return;
}
Note that in this case, str
contains the terminating end-of-line character. You could do
if (*str != '\0')
str[strlen(str) - 1] = '\0';
to remove it. (Also, as some others already pointed out, the “haystack” argument to strstr
goes first.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.