2

I have a program, which should output the track name and number based on a text input (e.g. input 'town' should output "Track 1: 'Newark, Newark - a wonderful town'") but the output is currently empty (nothing is returned, the program just stops executing without any errors). Here's the program:

#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;
}

Please help :)

John Doe
  • 291
  • 1
  • 10

1 Answers1

4
fgets(search_for, 80, stdin);

catches the \n newline character trailing the proper string input made by the press to Return and writes it into search_for.


The best way to remove it is best-explained in this answer to Removing trailing newline character from fgets() input.

Use strcspn() by:

search_for[strcspn(search_for, "\n")] = 0;

before the call to

find_track(search_for);

to remove or better said replace it with \0.


The whole code shall be then:

#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);
    search_for[strcspn(search_for, "\n")] = 0;    // here is the change.
    find_track(search_for);
    return 0;
}