strstr not returning desired result

Viewed 82

Can you identify the error in this code, it's not being able to print the song even though I pass the valid parameters to find

#include <stdio.h>
#include <string.h>

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[]) 
{
    int i;
    for(i = 0; i < 5; i++) {
        if (strstr(tracks[i], search_for)) {
            printf("Track %i: '%s'\n", i, tracks[i]);
        }
    }
}

int main() {
    char askedSong[80];
    printf("%s", "Hey buddy, what is the good one today? ");
    fgets(askedSong, sizeof(askedSong), stdin);
    find_track(askedSong);
    return 0;
}
4 Answers
  1. Suppose you can get "\n" at the end after fgets. Need to trim it (if you are inputing from the keyboard). You can try to run using file input: yourexefile.exe < input.txt > output.txt and find that it works somehow
  2. Suppose you should break after finding the result in the cycle.

The problem here is that fgets includes the trailing newline '\n' in askedSong.

Here's how I found it --- I ran the program in a debugger and put a breakpoint in find_track(). Then when prompted I put in "girl" on the command line and saw that the argument to the function is "girl\n".

Here's what I see in the debugger:

Hey buddy, what is the good one today? girl

Breakpoint 1, find_track (search_for=0x7fffffffd9c0 "girl\n") at test.c:15
15      for(i = 0; i < 5; i++) {
(gdb) 

There's a lot of wacky ways to trim that '\n' in C: Removing trailing newline character from fgets() input

probleme with fgets extra \n (enter)

#include <stdio.h>
#include <string.h>

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[]) 
{
    int i;
    for(i = 0; i < 5; i++) {
        if (strstr(tracks[i], search_for)!=NULL) {
            printf("Track %i: '%s'\n", i, tracks[i]);
        }
    }
}

int main() {
    char askedSong[80];
    printf("%s", "Hey buddy, what is the good one today? ");
    scanf("%s",askedSong);// try to use scanf to ovoid \n in the buffer
    find_track(askedSong);
    return 0;
}

fgets leaves the newline in the string. Easy fix:

fgets(askedSong, sizeof(askedSong), stdin);
askedSong[strcspn(askedSong, "\n")] = 0;
Related