[問題] while loop 無法正常結束

看板C_and_CPP作者 (.)時間12年前 (2013/06/27 09:15), 編輯推噓3(303)
留言6則, 2人參與, 最新討論串1/1
問題(Question): 我找不到自己程式裡面while loop 的bug 餵入的資料(Input): int or float 程式碼(Code):(請善用置底文網頁, 記得排版) while (flag){ cout << "Enter an odd number for dimension: " << endl; cin >> dimension; cout << dimension << endl; if (dimension % 2 == 0) cout << "Err: the dimension needs to be an odd int. \n"; else{ cout << "this is a " << dimension << "x" << dimension <<endl ; flag = false; } } 補充說明(Supplement): 當我送入 偶數例如4的時候 會正確的出現 Err並且要我重新輸入 當我送出float 3.2的時候 因為我宣告dimension為 int 所以會自己轉型成 3 印出 this is a 3x3 然後離開while 但是當我輸入4.2的時候 卻不斷在while裡面 並且不停印出印出 0 Err: the dimension needs to be an odd int. Enter an odd number for dimension: 0 Err: the dimension needs to be an odd int. Enter an odd number for dimension: 0 ..... 我看不出來為什麼會何會這樣 照理應該只會出現一個錯誤訊息並且要求使用者重新輸入 另外怎麼會有一個0 呢? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 204.96.168.3

06/27 11:21, , 1F
在 cin<<dimension<<endl; 之前加上
06/27 11:21, 1F

06/27 11:22, , 2F
cin.clear(); 和 fflush(stdin); 試試看吧。
06/27 11:22, 2F

06/27 19:01, , 3F
請別用 fflush(stdin)... 用 while(cin.get()!='\n'); 較好
06/27 19:01, 3F

06/27 19:02, , 4F
我寫的那個是一直吃字吃到 '\n' 為止
06/27 19:02, 4F

06/27 19:11, , 5F
冏。我忘記 fflush(stdin) 是 undefined behavior。
06/27 19:11, 5F

06/27 19:12, , 6F
多謝L大提醒。
06/27 19:12, 6F
文章代碼(AID): #1Hov8iJn (C_and_CPP)