ifstream "fail()" vs. "eof()" question.

R

Robbie Hatley

Say I have an ifstream object, like so:

#include <iostream>
#include <fstream>
int main(int, char* Sam[])
{
std::ifstream Bob;
Bob.open(Sam[1]);
std::string buffer;
while (42)
{
getline(Bob, buffer);
if (Bob.fail()) std::cerr << "Stream failed!" << std::endl;
if (Bob.eof())
{
std::cout << "eof" << std::endl;
break;
}
std::cout << buffer << std::endl;
}
return 0;
}

On my compiler, fail() will come up true whenever eof
occurs. And yet, I've read that fail() is supposed to
to be true only when a non-eof stream failure occurs:

http://www.cplusplus.com/ref/iostream/ios/fail.html

So, is my compiler messing up? Or is the info on that
web site wrong? They can't both be right.

--
Puzzled,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
http://home.pacbell.net/earnur/
 
P

P.J. Plauger

Say I have an ifstream object, like so:

#include <iostream>
#include <fstream>
int main(int, char* Sam[])
{
std::ifstream Bob;
Bob.open(Sam[1]);
std::string buffer;
while (42)
{
getline(Bob, buffer);
if (Bob.fail()) std::cerr << "Stream failed!" << std::endl;
if (Bob.eof())
{
std::cout << "eof" << std::endl;
break;
}
std::cout << buffer << std::endl;
}
return 0;
}

On my compiler, fail() will come up true whenever eof
occurs. And yet, I've read that fail() is supposed to
to be true only when a non-eof stream failure occurs:

http://www.cplusplus.com/ref/iostream/ios/fail.html

So, is my compiler messing up? Or is the info on that
web site wrong? They can't both be right.

Well, they could in this case. basic_ios::fail() returns
true if either badbit or failbit is set in the stream object.
getline typically fails when it encounters an eof instead
of a line. So you're probably seeing the eofbit that accompanies
failbit in this case.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top