Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

frstream problems

Status
Not open for further replies.

philrosenberg

Technical User
Dec 3, 2003
15
GB
I'm ripping my hair out over reading data in through an fstream.
I open the fstream and read the values in the file into a double then push them into a vector. Only problem is the values aren't being read.
is_open() returns true, but tellg() returns -1, and after trying to read in a value both the eofbit and failbit are set.
I am reusing the fstream object and the double after reading in data from another file. I've checked to make sure that the fstream is closed after its previous use, again using is_open(). The previous use works fine. I've tried renaming the file and recreating the file but it made no difference.

If anyone can think of why this should happen please let me know, a snippet of the code is below

double temp;
vector < double > separation;
int ypixels=673;

//some code to read in from other files

if(fin.is_open()) cout << "fin not closed" << endl;
fin.open("sep.txt", ios::in);
if(!fin.is_open())
{
cout << "cannot open sep.txt" << endl;
return 0;
}
cout << fin.tellg() << endl;
for(i=0; i<ypixels; i++)
{
fin >> temp;
if(fin.fail()) cout << "fail" << endl;
if(fin.eof()) cout << "eof" << endl;
if(fin.bad()) cout << "bad" << endl;
if(fin.good()) cout << "good" << endl;
separation.push_back(temp);
}
fin.close();

output is:
-1
fail
eof
 
That's why I hate reusing fstreams.
What are the flags set to before your call to: fin.open("sep.txt", ios::in);
Try doing fin.clear(); before you open the next file?
 
cheers cpjust
It was an issue with reusing the stream, The file before had fewer values in than it was supposed to so I kept reading in and there was nothing for it to read. I guess just closing it didn't clear the errors.

Thanks

Phil
 
Always call clear() after closing a stream if you intend to re-use it, so that those error bits are cleared.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top