468,504 Members | 1,924 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,504 developers. It's quick & easy.

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

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/
Jul 16 '06 #1
1 11761
"Robbie Hatley" <bo***********@no.spamwrote in message
news:BU*******************@newssvr14.news.prodigy. com...
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
Jul 16 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Anton Ishmurzin | last post: by
1 post views Thread by Vassilis Stratis | last post: by
6 posts views Thread by Ram Laxman | last post: by
4 posts views Thread by Gunnar | last post: by
4 posts views Thread by hall | last post: by
1 post views Thread by inkapyrite | last post: by
11 posts views Thread by enki | last post: by
9 posts views Thread by Charles F McDevitt | last post: by
2 posts views Thread by Karl | last post: by
7 posts views Thread by Boltar | last post: by
reply views Thread by NPC403 | last post: by
3 posts views Thread by gieforce | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.