看板 C_and_CPP 關於我們 聯絡資訊
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
WJAider:喔喔 還有 sync() ,推一個 07/08 11:15
james732:推,原來還有這招 07/08 11:50
anotherday:推! 07/08 12:39
xatier:還有這招! 07/08 13:07
lwecloud:又學到一招 07/08 13:20
angleevil:o.O此板強者很多 07/08 13:27
firejox:真可怕... 07/08 13:41
angleevil:cin.sync();->cin.ignore();也可 07/08 13:56
angleevil:只是要搭配numeric_limits<streamsize>::max() 07/08 13:57
tropical72:那個,姑且不論 sync(), ignore() 本身有一些差異, 07/08 13:59
tropical72:但此例,似乎 ignore 會比 sync 慢一點. 07/08 13:59
Favonia:一開始 EOF 程式就不會結束了... 還是說本來就要這樣 xDDD 07/08 20:13
我發現我誤解了 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)
loveme00835:害我手癢也想發一篇... 07/08 22:09
james732:板主快發吧 07/08 22:13