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-typevoid
butint
.scanf
can fail. Check the return-value.If successful, it returns the number of parameters assigned.
%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.Use
%71s
(buffer-size: string-length + 1 for the terminator)strstr
.