1

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

guskenny83
  • 1,117
  • 12
  • 25
  • "but then i get a seg fault when it is finished" - where exactly do you get it? and if it's in your overloaded operator>>, how is it defined? – codeling Oct 16 '13 at 10:06
  • sorry, i had a look and the seg fault is occurring in the overloaded operator>>() function in the line: getline(fin, line); – guskenny83 Oct 16 '13 at 10:18
  • so what i am looking for i guess is a way of testing if fin has another line, before the call to operator>>() – guskenny83 Oct 16 '13 at 10:19

1 Answers1

1

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.)

Community
  • 1
  • 1
Albert
  • 57,395
  • 54
  • 209
  • 347