Using strstr to determine if a given string contains a string with spaces [C]

3k views Asked by At

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);
}
2

There are 2 answers

0
Deduplicator On
  1. main does not have return-type void but int.
  2. scanf can fail. Check the return-value.
    If successful, it returns the number of parameters assigned.
  3. %s only reads non-whitespace, until the next whitespace (thus 1 word).
  4. %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)
  5. You swapped the arguments to strstr.
0
user3426575 On

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.)