Anas Ayubi
Anas Ayubi

Reputation: 257

String search in C

In the following code the strstr() function seems to not be responding appropriately - the if() statement is not run as strstr() consistently gives out a null pointer despite the fact that the input string (variable search_for) is present in the array. After hours of frustration I have now given up. Please help!

#include <stdio.h>
#include <string.h>
char tracks[][80] = {
    "impossible",
    "how to grow strong",
    "love is in the air",
    "3 prophets of everland",
    "home"
};
void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 5; i++)
    {
        if (strstr(tracks[i], search_for))
            printf("Track %i: %s", i, tracks[i]);
    }
}
int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);
    find_track(search_for);

    return 0;
}

Upvotes: 0

Views: 112

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84642

You can easily strip the '\n' character by overwriting it with a null-terminating character:

#include <stdio.h>
#include <string.h>
char tracks[][80] = {
    "impossible",
    "how to grow strong",
    "love is in the air",
    "3 prophets of everland",
    "home"
};
void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 5; i++)
    {
        if (strstr(tracks[i], search_for))
            printf("Track %i: %s", i, tracks[i]);
    }
}
int main(void)
{
    char search_for[80];
    size_t length = 0;

    printf("Search for: \n");
    fgets(search_for, 80, stdin);

    length = strlen (search_for);
    search_for[length-1] = 0;

    printf("%s\n", search_for);
    find_track(search_for);

    printf ("\n");

    return 0;
}

output:

$./bin/srchfor
Search for:
strong
strong
Track 1: how to grow strong

Upvotes: 0

wRAR
wRAR

Reputation: 25569

Your input string contains a newline \n. You could use a debugger to skip hours of frustration.

Upvotes: 6

Related Questions