Trouble using strstr after fgets

Discussion in 'C' started by p3tr0va, Jun 7, 2014.

  1. p3tr0va

    p3tr0va New Member

    Joined:
    Jun 7, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hi everybody.
    I want to use fgets to read a line of text and a word. The text is examined to find the word, but the word is never found even when the word is in the text.
    What am I doing wrong?
    Thanks.

    Code:
    #define TEXT_LEN 100
    #define WORD_LEN 20
    
      char text[TEXT_LEN];
      char word[WORD_LEN];
     
      printf("Enter the text to be searched:\n");
      fgets(text, TEXT_LEN, stdin);
    
      printf("Enter the word sought:\n");
      fgets(word, WORD_LEN, stdin);
    
      if(strstr(text, word))
        puts("The word sought was found");
      else
        puts("The word sought was not found");
     
  2. p3tr0va

    p3tr0va New Member

    Joined:
    Jun 7, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    The problem is the character '\n' at the final of the word. fgets reads the new line character. Use gets(word) instead of fgets(word, WORD_LEN, stdin).
     
  3. p3tr0va

    p3tr0va New Member

    Joined:
    Jun 7, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Thanks p3tr0va.
     
  4. p3tr0va

    p3tr0va New Member

    Joined:
    Jun 7, 2014
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    You're welcome.
     
  5. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Urm... no. gets will betray you as it offers no boundary check. There's nothing preventing a user from trying to stuff 100,000 characters into your 20 character array, and trash memory elsewhere.

    Code:
    char text[TEXT_LEN] = { 0 },
           *p;
    
    fgets(text, sizeof text, stdin);
    
    if((p = strchr(text, '\n')) != NULL)
        *p = 0;
    else
        while(getchar() != '\n') {}
    
     
  6. Elizabeth_Keen

    Elizabeth_Keen Banned

    Joined:
    Jun 6, 2014
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    It's because fgets stores the newline character so when strstr does a comparison it fails.
    From the main page:
    fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

    Innovative Web Apps here: ati-erp.com
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice