views:

1443

answers:

2

I have a sample txt file and want to read the contents of the file into an array of structs. My persons.txt file contains 5 arbitrary nos one on each line.

7
6
4
3
2

My program looks like this:

#include <iostream>
#include <fstream>

using namespace std;

struct PersonId
{
    typedef PersonId* ptr;
    PersonId();
    int fId;
}; 

istream& operator >> (istream& is, PersonId &p)
{
    is >> p;
    // return is;
    // return p.read(is);
}

// istream& PersonData::read(std::istream& is) 
// {
//  is >> fId;
//  return is;
// }


int main ()
{
    ifstream indata;
    int i, is;
    indata.open("persons.txt", ios::in); // opens the file

    if(!indata) 
    { // file couldn't be opened
          cout << "Error: file could not be opened" << endl;
          exit(1);
    }

    int n = 5;
    PersonId* p;
    p = (PersonId*) malloc (n * sizeof(PersonId));

    while ( !indata.eof() )
    { // keep reading until end-of-file
     // p[i].read();
     indata >> is;
     i++;
     cout << "The next number is "<< is << endl;
            cout << "PersonId [" << i << "] is " << p[i].fId << endl;
        // indata >> is; // sets EOF flag if no value found
    }
    return 0;
}

My output looks like this:

test6.cpp: In function ‘std::istream& operator>>(std::istream&, PersonId&)’:
test6.cpp:27: warning: control reaches end of non-void function
The next number is 7
PersonId [1] is 0
The next number is 6
PersonId [2] is 0
The next number is 4
PersonId [3] is 0
The next number is 3
PersonId [4] is 0
The next number is 2
PersonId [5] is 0
+2  A: 
istream& operator >> (istream& is, PersonId &p)
{
    is >> p.fId;
    return is;
}

(Reading the member fId of p, not the entire structure)

And the the while in main, read the structure, not a value:

instead of

indata >> is;

put

indata >> p[i];
Cătălin Pitiș
Also, initialize i to zero before the while loop and move i++ AFTER your cout.
ScottTx
struct PersonId{ int fId;}; struct PersonData{ public: typedef PersonData* Ptr; PersonData(); PersonId fId; istream};istream return is;}istream return p.read(is);}How will indata >>p[i] work in this scenario??
vivekv80
A: 

See Neil Butterworth's reply to http://stackoverflow.com/questions/730910/ifstream-object-eof-not-working for how to correctly read from an istream

tragomaskhalos
I avoided using getline() bcos in the future I will have lot of numbers in one line, which will be the items of the same structure.
vivekv80
Getcha, but I was more worried about your use of eof().
tragomaskhalos