ling
ling

Reputation: 10017

Can this code work with fgets?

The following code works with scanf, but I don't know how to make it work with fgets (the search always fails), could you help me please (I'm a beginner in C) ?

And if possible, could you tell me why it doesn't seem to work with fgets?

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


int main(){
    char word[80];
    puts("Hello, type a word: ");
    fgets(word, 80, stdin);
//    scanf("%79s", word);

     for( int i= 0; i < 5; i++){
        if( strstr(tracks[i], word) ){
            printf("Found the track: %s\n", tracks[i]);
            break;
        }
     }


    return 0;
}

Upvotes: 2

Views: 61

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The difference between fgets(word, 80, stdin) and scanf("%79s", word) is that fgets one will include '\n' before null terminator, while scanf would not. That is why strstr returns NULL with fgets: there is an unmatched '\n' at the end.

There are two general approaches to making the strings equal again - you could either remove the '\n' from the end of the word (preferred), or add '\n' to the end of the words that you search (not recommended).

int len = strlen(word);
if (len != 0 && word[len-1] == '\n') {
    word[len-1] = '\0';
}

Upvotes: 5

Related Questions