C Code for string matching [Head First C] doesn't seem to work

#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); getch(); return 0; } 

This is the code obtained directly from Head First C. This does not work. if I change the line in the main

 char search_for[80]; 

to

 char *search_for = "town" 

This gives me the expected result. I do not understand why this does not work. I understand that directly embedding the code and telling you to find errors here is not very acceptable, but I think it is a very small piece of basic code, so it will do it.

thanks

+4
source share
2 answers

The problem with the above code is that it does not take into account the fact that fgets leaves a newline in a line . Therefore, when you type town and press enter , you will end up looking for "town\n" .

A cheap way to solve this problem would be to fix the line after calling fgets

 search_for[strlen(search_for) - 1] = 0; 
+4
source

As @cnicutar already pointed out, fgets leaves the string string char (code 10) in the string. You can find it yourself, iterating over a char array and printing character codes and searching for special characters in the ASCII code table (http://www.asciitable.com/):

 int main() { int i; char search_for[80]; printf("Search for: "); fgets(search_for, 80, stdin); scanf("%79s", search_for); // print index, char code, char itself for (i=0;i<80;i++) { printf("%d: %d %c\n", i, search_for[i], search_for[i]); } find_track(search_for); getch(); return 0; } 

The output will be:

 ... 0: 116 t 1: 111 o 2: 119 w 3: 110 n 4: 10 5: 0 ... 

You can use the "scanf" function and limit the number of characters read to 79 (1 char reserve for a NULL char at the end of the line, since the buffer contains a maximum of 80 characters). See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ for reference.

 int main() { char search_for[80]; printf("Search for: "); scanf("%79s", search_for); find_track(search_for); return 0; } 
+1
source

All Articles