technextgen
technextgen

Reputation: 87

Why is the program not giving me the desired output? What's gone wrong?

So I'm new to C programming, I saw a program in one of the books and tried runnning it. The program takes a string and checks the string location in the master string and outputs the string id and the string.

#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 search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

This is the terminal output:

PS C:\Users\G\Documents\C programs> gcc try1.c -o try1 -Wall -pedantic -std=c99
PS C:\Users\G\Documents\C programs> ./try1
Search for: town
PS C:\Users\G\Documents\C programs> 

As you can see, it should have outputted the track ID and the track. But it isn't, any sort of help is appreciated!

Upvotes: 0

Views: 59

Answers (1)

Aplet123
Aplet123

Reputation: 35512

fgets leaves a trailing newline, so you're actually searching for "town\n" instead of "town", which obviously won't yield matches. Trim the newline:

fgets(search_for, 80, stdin);
search_for[strcspn(search_for, "\n")] = '\0';

Upvotes: 5

Related Questions