Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String example doesn't behave as expected

Tags:

c

I'm learning C and I've been following the "Head First C" book. I arrived at an example where this is the resulting code:

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

I've double, triple, and quadruple checked. This code is exactly the same as the example in the book. At first I made it my own so that I'm not just copying without learning, but when I didn't work I literally copied it to make sure. The code askes for a string, and then prints any tracks containing the string you gave it. In the book, when the example code is run, the string given was "town", and the code prints "Newark, Newark - A wonderful town." However, when I do the exact same thing it prints nothing but a newline.

I can't stress enough, this code is exactly the same as in the book, yet it behaves differently. Can someone see why?

like image 353
user3674736 Avatar asked Mar 03 '15 19:03

user3674736


1 Answers

The problem is in this statement

fgets(search_for, 80, stdin);

Function fgets includes in the string the new line character. You have to remove it from the string. For example

size_t n = strlen( search_for );

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

From the C Standard

Description

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

like image 110
Vlad from Moscow Avatar answered Oct 18 '22 19:10

Vlad from Moscow