[問題] getc讀文字檔會漏字

看板C_and_CPP作者 (Crysis)時間12年前 (2012/06/01 15:17), 編輯推噓0(003)
留言3則, 3人參與, 最新討論串1/1
問題(Question): 用getc每次讀取檔案100個char並印出, 然後換行讀取下100個char 發現前面100個char都正常, 但第101個char卻會被漏掉(沒讀到) 餵入的資料(Input): 某個檔案內存一段文字(ascii), 沒有換行符號: "You needn't look for it," said Della. "It's sold, I tell you--sold and gone, too. It's Christmas Eve! 共102個char 預期的正確結果(Expected Output): 第一行印到: ...Christmas Ev 第二行印 : e! 錯誤結果(Wrong Output): 第一行印到: ...Christmas Ev 第二行印 : ! 第二輪的第一個字元'e'被漏掉了 程式碼(Code): FILE * fptr = fopen 檔案; char ch; int row=0; for(row=0; row<2; ++row){ int count = 0; while((ch=getc(fptr))!=EOF){ if(count<100){ printf("%c", ch); ++count; } else{ printf("\n"); break; } } } P.S. 如果用do{ getc }while( condition );的話就正常了 但是仍然想不通為何原本的寫法不對..麻煩指教, 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.160.66.223 ※ 編輯: Crysis 來自: 118.160.66.223 (06/01 15:19)

06/01 15:23, , 1F
break的那次吃到的ch沒有被印出來
06/01 15:23, 1F

06/01 15:27, , 2F
謝謝~!我剛po完也想到了, 因為break條件是count
06/01 15:27, 2F

06/01 15:39, , 3F
感謝分享
06/01 15:39, 3F
文章代碼(AID): #1Fo6obL7 (C_and_CPP)