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