Feb 1, 2017 at 8:11am UTC
cout << *p[i] << "\n";
is this statement wrong? im trying to access the elements in the the array of DATA.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#include <iostream>
#include <fstream>
using namespace std;
class DATA
{
private :
int key;
string firstName;
string lastName;
float GPA;
public :
friend ifstream &operator >>(ifstream & ,DATA &);
friend ostream &operator <<(ostream &,DATA);
int getkey()
{
return key;
};
};
ifstream &operator >>(ifstream &in,DATA &d)
{
in >> d.key >> d.firstName >> d.lastName >> d.GPA;
return in;
}
ostream &operator <<(ostream &out,DATA d)
{
out << d.key << " " << d.firstName << " " << d.lastName << " " << d.GPA;
return out;
}
class List
{
private :
DATA **p;
public :
List();
int insertDATA (string ,int );
void getDATA(int );
};
void List::getDATA(int i)
{
cout << *p[i] << "\n" ;
}
int List::insertDATA(string fileName ,int i)
{
DATA d;
ifstream in;
in.open(fileName.c_str());
while (in >> d)
{
p[i] = new DATA(d);
i++;
}
return i;
}
List::List(void )
{
p = new DATA*[10];
}
int main(int argc,char *argv[])
{
List list;
int counter = 0;
char option;
string fileName;
if (argc == 3)
{
fileName = (argv[1]);
while (counter < 10)
{
counter = list.insertDATA(fileName ,counter);
}
for (int i = 0; i < counter; i++)
{
list.getDATA(i);
}
ofstream out;
out.open(argv[2]);
}
else
{
cout << "can't open input file and output file: put input file name then follow by output file name" ;
}
}
Last edited on Feb 1, 2017 at 8:12am UTC
Feb 1, 2017 at 8:58pm UTC
The syntax is fine, but why not just use a vector<Data> instead of making your own complex vector collection? Consider the bugs that you already have in the code:
- It leaks the array, and the DATA objects that the array points to.
- If you copy a List, both lists will point to the same data. So who is then responsible for deleting it?
- The list class doesn't know how many items are in its array. Only the main program knows that. It would make more sense to have List aware of how many items are in it and relieve main() of this burden.