简体   繁体   中英

Why fgets doesnt work in this scenario, where scanf works?

In the below code I am using fgets to save the input for a string. With fgets the desired strcmp() on my search function,display(), won't work but with scanf() it does work. Why is this happening?

int main(){

 char end[]="end" ;
 FILE *file ; 
 char searchfor[30] ;

   if( (file=fopen("c:\\Users\\Konpoul\\Desktop\\GrGames.txt", "r")) ==NULL   ){
        printf("cannot open file");
        exit(1) ;
    }

    fileRead(file) ;  // This is a function 

    while( strcmp(searchfor,end) !=0 ){ 
    fgets(searchfor,sizeof(searchfor),stdin) ; 
    //scanf("%s",&searchfor) ; 
    display( searchfor) ;     // Inside this function I strcmp(a_name , searchfor)
    }
     printf("end") ; 
}

Here is the display function that doesn't work as expected

 void display(char *name){
     for(int i =0 ; i<N ; i++){
         if( strcmp(player[i].name , name )==0 ){
             printf("Name :%s  date: %d  Goals: %d  Meters Runned: %d  Time played : %f" ,player[i].name ,player[i].date ,player[i].goals,player[i].passes ,player[i].timepl) ; 
          }
     }
 }

After a little research, I realized the problem so I post my findings here.

Taking a close look at the documentation,it explains that fgets reads characters from the current stream position to and including the first newline character , to the end of the stream, or until the number of characters read is equal to numChars - 1.

So parsing the searchfor variable , with "end",what gets stored in the (buffer)searchfor variable is "end" when I use scanf() but "end\n" when I use fgets(). That is because there is enough space in the searchfor[30] to include the newline charachter.

Thus, the strcmp() would compare "end" with "end\n" never returning 0 as a result. So solutions to my problem are that I either use scanf() for parsing or that I eliminate the newline charachter "\n" from the parsed variable.

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