std::istream& safeGetline(std::istream& is, std::string& t)
{
t.clear();
//这比使用std::istream逐个读取它们要快。
//以这种方式使用streambuf的代码必须由sentry对象保护。
// sentry对象执行各种任务,如线程同步和更新流状态。
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
for(;;) {
int c = sb->sbumpc();
switch (c) {
case '\r':
c = sb->sgetc();
if(c == '\n')
sb->sbumpc();
return is;
case '\n':
case EOF:
return is;
default:
t += (char)c;
}
}
}
例子:
int main()
{
std::string path = "end_of_line_test.txt"
std::ifstream ifs(path.c_str());
if(!ifs) {
std::cout << "Failed to open the file." << std::endl;
return EXIT_FAILURE;
}
int n = 0;
std::string t;
while(safeGetline(ifs, t)) //<---- INFINITE LOOP happens here. <----
std::cout << "\nLine " << ++n << ":" << t << std::endl;
std::cout << "\nThe file contains " << n << " lines." << std::endl;
return EXIT_SUCCESS;
}