Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search text using strstr function in C [duplicate]

Tags:

c

text

search

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

like image 576
Chozo Qhai Avatar asked May 23 '26 12:05

Chozo Qhai


1 Answers

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);
like image 93
Gangadhar Avatar answered May 25 '26 04:05

Gangadhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!