1
我不知道爲什麼istream :: get sets failbit和eofbit在一起。爲什麼istream :: get sets failbit和eofbit在一起?
std :: getline的行爲有所不同:它在遇到文件結尾時設置eofbit,而當您嘗試讀取文件末尾時會設置失敗位。所以,你可以寫:
while (std::getline(is, s) {
blablabla... // gets executed once after end of file has been reached
}
而如果你定義一個標準::你自己getSthg功能得到
std::istream& myOwnGetLine(std::istream& is, std::string& s) {
char c;
while (is.get(c)) {
blablabla...
}
return is;
}
則:
while (myOwnGetLine(is, s)) { // fails if eof has been reached
blablabla // won't get executed for the last line of the stream
}
所以:我究竟做錯了什麼?該變通,我想出了是:
std::istream& myOwnGetLine(std::istream& is, std::string& s) {
*if (is.rdstate() & std::ios::eofbit) {
is.clear(std::ios::failbit);
return is;
}*
char c;
while (is.get(c)) {
blablabla...
}
*if (is.rdstate() & std::ios::eofbit) {
is.clear(std::ios::eofbit);
}*
return is;
}
但是,這並不健全的權利...