I was going through some exercises from the Head First C book. And there's one jukeBox program.
Source is here:
#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;
}
I'm using terminal to compile and see output of the program with gcc version 4.8.2 like:
gcc pr.c -o pr
And whenever I try to run the program and enter search string I get no output. Program just finishes execution and exits.
Also I want to mention that I tried to compile this code on ideone.com here.
What problems there might be? Terminal displays no output at all.
fgets
reads newline and put it in the buffer. So the string you type is never found in the array. Modify the code to suppress the newline after input, like this : search_for[strlen(search_for)-1]='\0';
. That should work better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With