Possible Duplicate:
End of File in C++
I wrote a function to read data from a .txt file, but when I call it, it keeps crashing. Here's the code:
void beolvas(vector<int> &charge, vector<int> &deliver, vector<Robot*> &robots) { string s; ifstream f; do { cout << "Add meg a filenevet" << endl; cin >> s; f.open(s.c_str()); } while (!f.good()); cout << "adatok beolvasasa..." << endl; int napok; if (!(f >> napok)) throw 1; charge.resize(napok); deliver.resize(napok); for (int i = 0; i<napok; i++) { if (!(f>>charge[i])) throw 1; if (!(f>>deliver[i])) throw 1; } string type, name; int battery; while (!f.eof()) { cout << " a "; if (f>>type && f>>name && f>>battery) { if (type=="Mac") { Mac r = Mac(name,battery); robots.push_back(&r); }; if (type=="Eco") { Eco r = Eco(name,battery); robots.push_back(&r); }; if (type=="Pro") { Pro r = Pro(name,battery); robots.push_back(&r); }; }; }; } It seems the problem occurs in the while loop. If I want to read from a 3 row long text, I get 4 letter a-s on the screen (I have the program print one before reading every row).
Is f.eof() not the function I need to use here?
eof()is always wrong. There are hundreds of duplicates on SO.