No output in terminal (Head First C)


I went through some exercises from the book Head First C. And there is one jukeBox program.
The 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 use the terminal to compile and view the output of a program with gcc version 4.8.2, for example:

 gcc pr.c -o pr 

And whenever I try to run a program and enter a search string, I get no output. The program simply terminates and terminates.

I also want to mention that I tried to compile this code on ideone.com here .
What problems can be? The terminal does not display output at all.

+6
source share
2 answers

fgets reads a new line and puts it in the buffer. Therefore, the string you enter is never found in the array. Change the code to suppress a new line after input, for example: search_for[strlen(search_for)-1]='\0'; . This should work better.

+7
source

Put this code before calling the function.

 search_for[strlen(search_for)-1]='\0'; 

You will get the correct result.

0
source

Source: https://habr.com/ru/post/980364/


All Articles