I am trying to read data from a file into an array. The array size is uknown before I open the file and count the number of data points. The function I have in mind is the following
Expand|Select|Wrap|Line Numbers
- void read_data(char *file,int &ndata,double *x,double *y)
- {
- //Read the data from the file and store it in memory
- //This reads the data stored in the two column file and stores it in memory
- ifstream data;
- data.open(file,ios_base::in);
- if(!data){
- cerr<<"Could not open the file"<<endl;
- cerr<<"Calculation will not occur\n";
- }
- else{
- ndata=0; // Read the number of data points from the file
- while(data.ignore(1280,'\n'))
- ++ndata;
- data.clear();
- data.seekg(0);
- ndata--; // Overcounts the number of data points by one
- cout<<"There are "<<ndata<<" lines of data\n";
- x=new(double [ndata+1]); // Resize the arrays according to the number of data points
- y=new(double [ndata+1]);
- for(int i=1;i<=ndata;i++){ // Read the data into the arrays
- data>>x[i];
- data.ignore(100,',');
- data>>y[i];
- }
- data.close();
- }
- }
Expand|Select|Wrap|Line Numbers
- int _tmain(int argc, _TCHAR* argv[])
- {
- //Step One: Read the data in from the file
- int ndpts=0;
- double *x=0; // Declare the pointers for the arrays to store the data
- double *y=0;
- // Some file names
- char *f1="Rib_InP_W_1.0_E_0.2_T_0.3_overlap_versus_offset_straight_bend_1.txt";
- char *f2="Rib_InP_W_1.0_E_0.2_T_0.3_overlap_versus_offset_straight_bend_10.txt";
- char *f3="Rib_InP_W_1.0_E_0.2_T_0.3_overlap_versus_offset_straight_bend_21.txt";
- read_data(f1,ndpts,x,y); // Read the data from the file
- for(int i=1;i<ndpts;i++){
- cout<<i<<" , "<<x[i]<<" , "<<y[i]<<endl; //Crash and burn!!
- }
- delete[] x;
- delete[] y;
- system("PAUSE");
- return 0;
- }
Thanks.