2017-02-13 25 views
0

我正在寫一chat server program作爲我的網絡實驗室的一部分,當我發現一個很奇怪的現象:奇怪的運行時的問題:printf的停止工作中途

 printf("Recieved login info.\n"); //works 
     printf("Username: %s\n", ui->username); //works 
     printf("Passward: %s\n", ui->password); //works 

     //TO_AUTHENTICATE, if failure, send appropriate reply 
     printf("makeitwork"); //does not work 
     while(ui != NULL) 
     { 
       printf("here2");//does not work 
       if(strcmp(ui->username, record.username) == 0 && strcmp(ui->password, record.password) == 0) 
       { 
         strcpy(userRecords[sockfd].username, record.username); 
         userRecords[sockfd].status = ONLINE; 

         printf("Successfully authenticated %s.\n", userRecords[sockfd].username); 

       //  sendOnlineUsers(sockfd, registeredUsers); 

         return SUCCESS; 
       } 
       ui = ui->next; 
     } 

在上面的代碼段中,第一,第二和第三個printf語句有效,但從第四個起,它不起作用。

但是,如果我註釋掉if聲明printf("here2");,一切正常。

我用gdb逐行地執行該程序行:

(gdb) 
Recieved login info. 
94  printf("Username: %s\n", ui->username); 
(gdb) 
Username: user-1 
95  printf("Passward: %s\n", ui->password); 
(gdb) 
Passward: pass 
98  printf("makeitwork"); 
(gdb) 
99  while(ui != NULL) 
(gdb) 
101   printf("here2"); 
(gdb) 
102   if(strcmp(ui->username, record.username) == 0i)//&& strcmp(ui->password, record.password) == 0) 

的printf的正在執行,但也有是在終端上沒有輸出。

發生了什麼事?

回答

1

您需要刷新緩衝區

添加

fflush(stdout); 

printf後,你沒有\n在年底做

+0

你是對的。我放了一個'/ n',現在它正在工作。你能解釋發生了什麼,我會接受你的答案。 – daltonfury42

+0

'Printf'將東西放入緩衝區。 '\ n'刷新緩衝區並將其發送到終端。如上所述發送新行或刷新緩衝區 –