c++ - calculate sum of integers from a file using structure pointer -
struct data { int *pdata; int nsize; int nsum; int nmax; int nmin; float fmean; }; struct data readdatafile(const char *pfilename); int main(void) { data stdata = readdatafile ("data.txt"); printf("we read %d numbers\n", stdata.nsum); printf("sum: %d\nmean: %f\nmax: %d\nmin: %d\n", (float)stdata.nsum / stdata.nsize, stdata.nmax, stdata.nmin); return 0; }
how assign values data.txt
*pdata
, calculate nsum
? have done storing values array. unable assign , complete using pointer?
i did using arrays below.
if (infile.is_open()) { while (infile.good()) { infile.getline(cnum, 256, ' '); arrays[count]= atoi(cnum) ; ++count ; } infile.close(); min = arrays[0]; max = arrays[0]; for(int j=0; j<count; j++) { if(min > arrays[j]) min = arrays[j]; if(max < arrays[j]) max = arrays[j]; sum = sum + arrays[j]; } mean = sum/count; cout<<"sum= "<<sum<<"; min= "<<min<<"; max= "<<max<<"; mean= "<<mean<<"\n"; }
but how use structure same??
pdata
should dynamically allocated array. number of elements of file , allocate memory :
your_struct.pdata = new int[your_struct.nsize];
then can fill int
values in file , use array calculate sum, max, min , mean.
and don't forget delete[] your_struc.pdata
when you're done it.
Comments
Post a Comment