guskenny83
guskenny83

Reputation: 1373

finding the end of a filestream

i am trying to read tokenised data from a text file into a vector of pointers by overloading the operator>>() function in a custom class Customer. my code works fine to read them in through the whole file, but then i get a seg fault when it is finished

here is my code:

int line = 0;
vector<Customer *> customers;
ifstream fin("customers.txt", ios_base::in);

while (fin)
{
    Customer *temp = new Customer();
    line++;
    try
    {
        fin >> *temp;
        customers.push_back(temp);
    }
    catch(boost::bad_lexical_cast&)
    {
         cerr << "Bad data found at line " << line
             << " in file customers.txt" << endl;
    }
}

assume that the overloaded operator>>() function works to read a line in with getline() and inserts the data into the temp pointer to Customer, throwing a bad_lexical_cast if any invalid data is found..

i realise i can change:

while (fin)

to:

while (fin >> *temp)

but i want to keep the try/catch block, as if bad data is found i just want it to skip that line and continue to the next one.

is there anything i can do to test if the next line is there without actually pulling it? similar to the java hasNextLine in the scanner class?

any help would be greatly appreciated

Upvotes: 1

Views: 103

Answers (1)

Albert
Albert

Reputation: 68160

You must check the output of fin >> *temp. That returns false if it fails reading (i.e. end-of-file).

You can just change that line to:

if(!(fin >> *temp)) break;

(See also here for an answer to a similar problem/question.)

Upvotes: 1

Related Questions