Re: [問題] 只允許輸入數字,非輸入數字會迴圈請你 …
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間15年前 (2011/07/08 10:15)推噓9(9推 0噓 5→)留言14則, 10人參與討論串3/4 (看更多)
cin 的簡單解法:
int score;
cin >> score;
while(cin.fail() && !cin.eof()){
cin.clear(); // 清除 error flag
cin.sync(); // 清除 buffer 中的無效字元
cin >> score;
}
if(cin.eof())
throw runtime_error("EOF during input")
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.32.15.163
推
07/08 11:15, , 1F
07/08 11:15, 1F
推
07/08 11:50, , 2F
07/08 11:50, 2F
推
07/08 12:39, , 3F
07/08 12:39, 3F
推
07/08 13:07, , 4F
07/08 13:07, 4F
推
07/08 13:20, , 5F
07/08 13:20, 5F
推
07/08 13:27, , 6F
07/08 13:27, 6F
→
07/08 13:41, , 7F
07/08 13:41, 7F
→
07/08 13:56, , 8F
07/08 13:56, 8F
→
07/08 13:57, , 9F
07/08 13:57, 9F
推
07/08 13:59, , 10F
07/08 13:59, 10F
→
07/08 13:59, , 11F
07/08 13:59, 11F
推
07/08 20:13, , 12F
07/08 20:13, 12F
我發現我誤解了 fail bit
http://www.cplusplus.com/reference/iostream/ios/fail/
The function returns true if either the failbit or the badbit is set.
At least one of these flags is set when some error other than reaching
the End-Of-File occurs during an input operation.
雖然講了 "other than reaching the End-Of-File" 不過的確遇到 EOF 的時候
fail bit 也會被設為 true.
不過這邊也只能用 fail bit 去檢查 (bad bit 應該是用於 I/O error)
所以前面要加上對 eof 的處理
※ 編輯: littleshan 來自: 118.168.83.226 (07/08 20:37)
※ 編輯: littleshan 來自: 118.168.83.226 (07/08 20:50)
推
07/08 22:09, , 13F
07/08 22:09, 13F
→
07/08 22:13, , 14F
07/08 22:13, 14F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 4 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章