2

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;
}
1
  • 2
    fgets leaves the newline in the string, scanf doesn't. Commented Aug 27, 2014 at 17:13

1 Answer 1

5

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';
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Minor addition: scanf("%79s" will not scan any white-space whereas fgets() will (up to the first '\n').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.