为什么fgets在这种情况下不能工作,而scanf可以工作?

问题描述 投票:0回答:1

在下面的代码中,我使用fgets保存字符串输入。使用fgets在我的搜索功能display()上所需的strcmp()无法正常工作,但使用scanf()可以正常工作。为什么会这样?

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

这里是显示功能无法正常工作

 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) ; 
          }
     }
 }
c scanf fgets strcmp
1个回答
0
投票

经过一番研究,我意识到了这个问题,所以我将发现发表在这里。

仔细阅读文档,它解释说fgets从当前流位置读取字符到 包括第一个换行符,直到流的末尾,或者直到读取的字符数等于numChars-1。

因此解析searchfor variable,以“ end”表示,什么存储在当我使用scanf()时,(buffer)searchfor变量为“ end”,而当我使用fgets()时为“ end \ n”。这是因为searchfor [30]中有足够的空间来包含换行符。

因此,strcmp()会将“ end”与“ end \ n”进行比较,结果从不返回0。 因此,解决此问题的方法是,我使用scanf()进行解析,或者从解析的变量中消除了换行符“ \ n”。

© www.soinside.com 2019 - 2024. All rights reserved.