In the book Head First C, fist edition, there is this progam:
#include <stdio.h>
#include <string.h>
char tracks[][80] = {
"I left my hearth 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;
}
However, when compiled and tested, you don't get the expected results. After breaking my head for a bit, I decided to look for the documentation for fgets, I discovered that the function reads up to an including a newline character, which is why no matter what I search for, I never get the expected result. However, in the book they say the program works when tested. Is this a book error, or am I missing something?
PS. the error can be easily fixed using scanf, which becomes obvious once you know why the program doesn't work as expected.
PS2. I remember C++ has some syntax to ignore the newline character. Does C have something similar?