Off-Topic > Off-Topic - Tiny Core Lounge

Small C Program

(1/2) > >>

I decided that this summer would be a good time to study C. In the book that I'm reading, there was this small program:
--- Code: (c) ---#include <stdio.h>
#include <string.h>

char tracks[][80] = {                                           //a list of songs that the user can search through
"I left my heart in Harvard Med School",
"Newark, Newark - a wonderful town",
"Dancing with a dork",
"From here to maternity",
"The girl form Iwo Jima",

void find_track(char search_for[]){
int i;
for (i = 0; i < 5; i++){                                                //loop through our array
if (strstr(tracks[i], search_for))                          //check if the user's search term is in this string
printf("Track %i: '%s'\n", i, tracks[i]);        //if so, the print the track number and title

int main()
char search_for[80];
printf("Search for: ");             
fgets(search_for, 80, stdin); //get user input
find_track(search_for);         //send user input to the function
return 0;
--- End code ---
This code compiles fine under TinyCore Linux 4.5.3 and under cygwin + windows xp. Unfortunately, It doesn't run correctly under either of them.  This is very annoying, even if it is a first edition book. 
My guess is that it has something to do with "pointer decay".

Does anyone have any idea what is causing this odd bug?
(I realize that this isn't really related to Core and no one has any obligation to offer any help of any sort ;))

Your app is also reading the new-line character.

So you type "Iwo", the program searches for

which obviously doesn't match.

Hi nomer
Read this:
It includes a nice little example on how to strip that newline character that is causing you trouble.

Thank you both so much for the helpful replies. I solved the issue by changing
--- Quote ---fgets(search_for, 80, stdin);
--- End quote ---
--- Quote ---scanf("%79s",search_for);
--- End quote ---
I'll bookmark the other solution.

I'll also try to send some feedback to the author/publisher.


Hi nomer
Using scanf like that will remove the newline character. It will also only return the first word if you enter a phrase.
Using fgets and replacing the newline character with a zero as shown in the link I provided will allow your
program to match on phrases as well as individual words.


[0] Message Index

[#] Next page

Go to full version