0

Here's a C program that prints out a string after passing it a sub-string(like a search). The code runs successfully and as intended if i use 'scanf' to collect the sub-string, but abnormally if i use 'fgets', please i would love to know why, thank you for your time.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char track[][80] = {"I left my heart in Havard Med School",
"Newark, Newark - a wonderful town",
"Dancing with a Dork",
"From here to maternity",
"The girl from Iwo Jima",
};

void find_song(char *search)
{
    for(int i = 0; i < 5; i++){
        if(strstr(track[i], search))
            printf("Track %i: %s\n\n", i, track[i]);        
    }
}

int main(){
    char search[80];
    printf("search track: ");
    //fgets(search, 80, stdin);  initial line the book used
    scanf("%79s", search); // my line
    find_song(search);
}
Trip
  • 1
  • 1
  • https://stackoverflow.com/editing-help#code – mkrieger1 May 10 '23 at 22:15
  • Please take the time to [edit] and properly format your code. You can paste the code in, highlight it and hit the `{}` button in the question editor. – paddy May 10 '23 at 22:15
  • In what specific way is it abnormal when using `fgets`? – Retired Ninja May 10 '23 at 22:17
  • 1
    `fgets()` returns a string with a newline at the end, `scanf()` doesn't. – Barmar May 10 '23 at 22:17
  • Seems to work fine with either call for me: [Try it online!](https://tio.run/##bVHBSsNAEL3vVwyRQmJT24tYm@qpiBX0Ym9tkXWzSYYmu2WzbSiSb4@zSRtUHEIG3nsz82ZW7PejVIimuUIl8kMsYV7aGPVN9sh@QTl@/sUMqtRhTGTcgDVc7Nbb9XSyhQf48paQy8RCcYJMcmMBFTzzIzcxvMoY3kWmde6FzHuTFTe7ELoMI@BQaRVLkxxysLpSTrTgStA0qNBmJFhos3Pwk9EFtTeShFBwK41Ce3LMKpOQoskhcZJlpeEFC05MHTF21BhDgir@KLVK/db@dUkuRRawLwYUiTY@KnJNu0wiSnO4pTQcBi3diVxg4tMl6PO7A@A2hHOroBe52NO5bOJ7KyeDAc5gUG7UhtYDDOFSHEQXfVtct39WM@bMFByVTw4vbGu8G@bOHrGfczq8azwDL@jYJJW29DsuhOmEzNJzqzM7HpeCKyoe3N2XXr/IubQ/WA/XrGn@eZpv "C++ (gcc) – Try It Online") – ShadowRanger May 10 '23 at 22:18
  • @ShadowRanger Make sure your stdin ends with a newline. – Barmar May 10 '23 at 22:19
  • 1
    @Barmar: Ah, duh, TIO's `input` field didn't have the newline, where typing it manually would, that would explain it. – ShadowRanger May 10 '23 at 22:19
  • 1
    Another difference is that `%79s` only reads a single word, `fgets()` reads a whole line. – Barmar May 10 '23 at 22:20
  • Thank you all very much for your response. *fgets()* does infact returns a newline, i checked a similar question and was able to fix it with this line of code `search[strcspn(search, "\n")] = 0;` after *fgets()* – Trip May 10 '23 at 22:43

0 Answers0