精華區beta CKEFGISC-1st 關於我們 聯絡資訊
※ 引述《macpaul (還我建中自由)》之銘言: : 我想讓我的輸入可以判別是否是不是數值 : 若非數值 則重新輸入 : int test,N; : printf("Please input a variable N ( N <= 99 ) :"); : while ( scanf("%d",&N)==0 ) /*檢查輸入是否為數值*/ 這樣做是錯的 : { : printf("You input an unavailable word. Re-enter again.\n"); : getch(); : clrscr(); : printf("Please input a variable N ( N <= 99 ) :"); : } : 但實際上若我第一次輸入非數值 : 他就給我跑無限迴圈了ㄟ : 為什麼之後的scanf都沒有動作了呢? : (若把scanf寫在區塊中 他也不理我說……) : 請教原理與修改的方式 : 謝謝 在古典 C 語言的觀念裡(以及實作上),輸入輸出是當成循序檔來處理的。 scanf 的作用乃是把輸入裡面所需要的部分拿出來, 過多的部分仍然留在 buffer 裡面。 如果在一開始的時候,你輸入的是字串而非數值, 則 scanf 在抓資料的時候一看到 buffer 裡面是字串就假設數值為 0 , 然後把字串留在 buffer 裡面。 下次 scanf 要抓的時候,先檢查 buffer 裡面有沒有東西, 如果沒有才跟鍵盤要東西, 但是已經有啦,所以又發現 buffer 裡面是字串,於是又假設為 0 , 然後把字串仍然留在 buffer 裡面,這樣一直搞下去就變成 infinite loop 啦... 解決方法的話,我是記得有一整套函式專門處理這個 buffer , 至於名稱還是去找 bible 比較快。 -- "Nuclear" means "No Clear." We have the right of having a clear earth, not a nuclear earth. ----------------------------------------------------------------- Jeffrey P. Peng b86077@mail.ee.ntu.edu.tw -- ※ 發信站: 批踢踢實業坊(ptt.twbbs.org) ◆ From: ccserv1.ee.ntu.