I have a text file with six Product Codes, Product Names and Product Prices, grouped per line. Each line has a diferrent product. I used for
and fin
to read data. Now I want to add those data to an array.
The product codes are set as pcode
, product names as pname
, product prices as pprice
and the array as arrP[]
. I'm told to add those data to an array using setData
, for which I have a constructor in class Product
.
Data reading works. However I cannot understand how to use setData
to add those to arrP[]
. I've tried arrP[i].setData(pcode, pname, pprice);
in the same for
that reads the data but it's obviously wrong because it crashes when it's about to execute that line. Below I quote my code about this part.
This is the code of the function that reads the data and moves it to the array (N is defined as 6):
int addptoarray(ifstream &fin, Product arrP[])
{
Product p;
int pcode;
int i;
char pname[21];
float pprice;
n = 0;
for(i=0; i<N; i=i+1){
fin >> pcode;
fin.get(pname, 21);
fin >> pprice;
arrP[i].setData(pcode, pname, pprice);
n = n+1;
}
}
This is the part on main that triggers the function (N
is defined as 6):
[...]
addptoarray(infile, arrP[N]);
[...]
This is the code of the constructor for setData
in Product
class:
void Product::setData(int pcode1, char pname1[], float pprice1)
{
pcode = pcode1;
pname[21] = pname1[21];
pprice = pprice1;
}