I am working on this example in a C programming book and the strstr command is supposed to trigger the printf command when the value is true. It is trying to find a string within tracks and return which track it was found in. I have palyed around with this for over an hour and cant seem to find what is wrong. Currently it is not printing anything even when there is supposed to be a match.
#include <stdio.h>
#include <string.h>
char tracks[][80] = {
"Boston",
"Where the Streets Have No Name",
"Row Row Row your Boat",
"Gangsta Paradise",
"Yoda",
};
void findTrack(char searchFor[]){
int i;
for(i = 0; i < 5; i++){
if(strstr(tracks[i], searchFor))
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
int main(){
char searchFor[80];
printf("what is your string?: ");
fgets(searchFor, 80, stdin);
printf("searching for: %s", searchFor);
findTrack(searchFor);
return 0;
}
I recommend that you print out the search string as entered - you will probably find there is a newline character at the end of the line. You should include newlines in the strings to search for, or strip it from the input.
You might do this as follows:
char *p = strchr(searchFor, '\n');
if (p!=NULL) *p='\0';
Further, I would recommend that for "clean" code you should write
if(strstr(tracks[i], searchFor)!=NULL) {
this shows clearly that you understand that strstr
returns a pointer.