Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

c++ - checking for eof in string::getline

How do I check for end-of-file using the std::getline function? If I use eof() it won't signal eof until I attempt to read beyond end-of-file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The canonical reading loop in C++ is:

while (getline(cin, str)) {

}

if (cin.bad()) {
    // IO error
} else if (!cin.eof()) {
    // format error (not possible with getline but possible with operator>>)
} else {
    // format error (not possible with getline but possible with operator>>)
    // or end of file (can't make the difference)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...