Inputing from file to parallel arrays
Mar 27, 2010 at 12:54am UTC
I am trying to write a function that will input from a file to parallel arrays. i have a file that contains 4 columns of information and an unknown number of rows. I want to input each column into an array and return the total number of elements in an array
file looks like
3 12345 1 15.95
2 67800 3 50.00
4 32145 2 4.50
6 98765 1 75.00
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
int buildArrays( int ar1[], int ar2[], int ar3[], double ar4[] )
{
ifstream infile;
//Open the input file. If it fails to open, display an error message and
//end the program
infile.open( "data.txt" );
if ( infile.fail() )
{
cout << "data.txt failed to open" ;
exit( -1 );
}
int numElements = 0;
int num;
infile >> num;
while (!infile.eof())
{
ar1 [numElements] = num;
infile >> num;
ar2 [numElements] = num;
infile >> num;
ar3 [numElements] = num;
infile >> num;
ar4 [numSales] = ( double ) num;
numElements++;
infile >> num;
}
infile.close();
return numElements;
}
Last edited on Mar 27, 2010 at 12:58am UTC
Mar 27, 2010 at 12:06pm UTC
Are you having any problems with that?
Also, a little suggestion:
instead of
1 2 3 4 5 6 7 8 9 10 11 12 13
infile >> num;
while (!infile.eof())
{
ar1 [numElements] = num;
infile >> num;
ar2 [numElements] = num;
infile >> num;
ar3 [numElements] = num;
infile >> num;
ar4 [numSales] = ( double ) num;
numElements++;
infile >> num;
}
, why not write
1 2 3 4 5 6 7 8
while (!infile.eof()){
infile >> ar1 [numElements];
infile >> ar2 [numElements];
infile >> ar3 [numElements];
infile >> ar4 [numSales];
numElements++;
}
Is NumSales a global?
Topic archived. No new replies allowed.