3

I'm making a search program, but it does not output the sentences for my input. It shows nothing in the end. Just the 'search for:' in the line 1.

#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;
}

Using Visual Studio 2010 with C

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
Chozo Qhai
  • 283
  • 2
  • 10
  • 19

2 Answers2

3
fgets(search_for, 80, stdin); 

if you give input heart after you are pressing return key

fgets() reads newline into search_for

    Now search_for=="heart\n";

remove \n at the end of search_for

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

   find_track(search_for);
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • Another question : How to lowercase input characters using tolower functions ? – Chozo Qhai Oct 13 '13 at 11:02
  • `tolower()` Converts c to its lowercase equivalent if c is an uppercase letter and has a lowercase equivalent. If no such conversion is possible, the value returned is c unchanged.See examples which explains [tolower()](http://www.tutorialspoint.com/c_standard_library/c_function_tolower.htm) and [Here](http://www.cplusplus.com/reference/cctype/tolower/) – Gangadhar Oct 13 '13 at 14:51
0

Easiest solution is to replace:

fgets(search_for, 80, stdin); 

with

fscanf(stdin, "%s", search_for);

With this method, be careful not to enter more than 79 characters in your search though.

Baldrick
  • 11,712
  • 2
  • 31
  • 35
  • I would *not* recommend to replace `fgets` by `fscanf`, exactly because of the buffer overflow problem. In production code, this could be a potential security problem. – Martin R Oct 13 '13 at 09:25
  • Also those functions behave differently. `fscanf` reads only until any white space. – Martin R Oct 13 '13 at 09:27