Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

obooyo

macrumors newbie
Original poster
Jul 22, 2008
8
0
I am getting another weird behavior of the c++ fstream class. Suppose you have an empty file test.txt. The file exist, just that it is empty. Now try this:

Code:
#include <iostream>
#include <fstream>

int main()
{
	
	
	ifstream file ("test.txt");
	cout << file.eof() << endl;
	char garbage;
	file >> garbage;
	cout << file.eof() <<endl;
	return 0;
}

Your output will be:
Code:
0
1

Can anyone explain why this happens? I have a text file, which at times could be empty, and I want the program to read it, notice it's empty, and quit without getting any garbage out of it. Does anyone have a solution to get around this?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.