简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM