String example doesn't behave as expected

I study C, and I follow the book "Head First C". I came to an example where this is the resulting code:

#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 checked the double, triple and quadruple. This code exactly matches the example in the book. At first I did it on my own, not just to copy without studying, but when I was not working, I literally copied it to make sure. The code requests a line and then prints any tracks containing the line you gave it. In the book, when the example code was run, the line was "city" and the code prints "Newark, Newark is a beautiful city." However, when I do the same, it prints nothing but a new line.

I can’t emphasize enough, this code is exactly the same as in the book, but it behaves differently. Can anyone understand why?

+5
source share
1 answer

The problem is this statement

 fgets(search_for, 80, stdin); 

The fgets function includes a new line character in a string. You must remove it from the line. for instance

 size_t n = strlen( search_for ); if ( n != 0 && search_for[n-1] == '\n' ) search_for[n-1] = '\0'; 

From standard C

Description

2 The fgets function reads no more than the number of characters specified n from the stream pointed to by the stream to the array pointed to by s. No additional characters are read after the newline character (which is saved) or after the end of the file. A null character is written immediately after the last character is read in the array.

+7
source

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


All Articles