View previous topic :: View next topic |
Author |
Message |
micmac l33t
Joined: 28 Nov 2003 Posts: 996
|
Posted: Tue Sep 18, 2012 7:11 am Post subject: Why does this C program not work? |
|
|
Hello all,
this code is from O'Reilly's "Head First C":
Code: |
/*
* text_search.c -- search for a music track
*
*/
#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+1, tracks[i]);
}
}
int main(void)
{
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
|
It compiles fine, but it doesn't work. The return of strstr() is always "(nil)". I can't see why, because strstr() gets fed with two char*s.
Example:
Code: |
~/head-first-c $ ./0004-text_search
Search for: town
~/head-first-c $
|
Any idea what's wrong? |
|
Back to top |
|
|
GabrielYYZ n00b
Joined: 03 May 2012 Posts: 24 Location: Dominican Republic
|
Posted: Tue Sep 18, 2012 7:26 am Post subject: |
|
|
fgets leaves an extra newline ("\n") so it never matches.
add this after fgets but before find_track in main():
Code: |
int len;
len = strlen(search_for);
if(search_for[len-1]=='\n')
search_for[len-1]='\0';
|
|
|
Back to top |
|
|
eccerr0r Watchman
Joined: 01 Jul 2004 Posts: 9683 Location: almost Mile High in the USA
|
Posted: Tue Sep 18, 2012 7:28 am Post subject: |
|
|
Ugh... I'm forgetting my C after so much disuse.
Two problems I see that are related, first one more important:
1. When you fgets, the newline character is put into the string. Comparing for it will not work very well. You'll need to zap the carriage return, probably best to use search_for[strlen(search_for)-1]='\0'.
2. The tracks array does not have carriage returns in it, so that's why 'town' didn't match.
Helps?
Code: | int main(void)
{
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
search_for[strlen(search_for)-1]='\0';
find_track(search_for);
return 0;
}
|
No I did not look for buffer overflow issues, that is left as an exercise for the reader :D _________________ Intel Core i7 2700K/Radeon R7 250/24GB DDR3/256GB SSD
What am I supposed watching? |
|
Back to top |
|
|
micmac l33t
Joined: 28 Nov 2003 Posts: 996
|
Posted: Tue Sep 18, 2012 7:11 pm Post subject: |
|
|
Thank you both! Now it works.
I'll tattoo "fgets() may add a new line" on my forehead. |
|
Back to top |
|
|
GabrielYYZ n00b
Joined: 03 May 2012 Posts: 24 Location: Dominican Republic
|
Posted: Tue Sep 18, 2012 7:27 pm Post subject: |
|
|
micmac wrote: | Thank you both! Now it works.
I'll tattoo "fgets() may add a new line" on my forehead. |
Glad it works and don't feel bad about it, it's hard to find errors in a book which is supposed to teach you... |
|
Back to top |
|
|
|