C++ ifstream failbit being set

Recommended Posts

Hey everyone, I'm learning how to use ifstream/ofstream and manipulate strings using functions like strstr() and strcat() etc. Anyway, I wrote a basic program which worked fairly well except for one part which sets a failbit (program still operates fine if I clear() the fail bit but obviously that's bad practice). I simplified the code right down and removed all unnecessary parts and the error is being caused by this:
#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream fin("file.txt");

while (!fin.eof())
{
//Something wrong here
char tempUser[100];
fin.getline(tempUser, 100);
}

if (fin.fail())
{
cout << "Error: Ifstream failbit has been set."	<< endl;
return 1;
}
cout << "Process has been completed successfully." << endl << endl;

return 0;
}


Can someone please tell me why this causes an error? file.txt is just a text document with about 5 lines with each containing a different word no bigger than 7 characters. Cheers, Chris [Edited by - jpetrie on November 11, 2009 10:22:12 AM]

Share on other sites
Yes there is an empty line at the end of the file. In my program ofstream is used to output a username and password to the text file, so at the end of the output I was placing a new line so that two entries would not exist on the same line the next time.

I'll just change it to output a new line before each entry.

Thanks heaps, I didn't see that anywhere in the ifstream references on cplusplus.com, it was really frustrating to have an error like that.

Oh and yeah, I knew fail() checks for failbit and badbit, but for the simplified code that did the job :)

I'll make that edit now, thanks again.

Share on other sites
mattd    1078
Sorry! I deleted my post because I suddenly wasn't entirely sure of myself :]. Here it is again:

Do you have an empty line as the last line of your file.txt? istream::getline sets failbit if it stores no elements (and reads no elements from the stream), i.e., the last line before EOF is empty.

Also note that fail() actually checks for failbit or badbit being set.

That said, why not use std::strings and std::getline?
#include <string>while (!fin.eof()){	string tempUser;	getline(fin, tempUser);}

You could avoid the failbit being set by doing this:
while (fin.peek() != EOF){	string tempUser;	getline(fin, tempUser);}

Share on other sites
It's all good. I replied to it but looked like a bit of a tool because there was no post to reply to haha.

I fixed the newline issue and it's all good now. The important thing is I learned something new :)

Thanks for the help, I rated you as extremely helpful but since my rating is pretty average it wont do a great deal lol.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account