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 102 103 104
|
#include <iostream>
#include <fstream>
using std::cout;
void readFile();// just looking
int* readFile( const char* fname, int& rows, int& cols );// copies file data to array
void print( int* A, int rows, int cols );
void showColSums( int* A, int rows, int cols );
int main()
{
int Arows=0, Acols=0;
int* A = readFile( "arrData.txt", Arows, Acols );
if( A )
{
print( A, Arows, Acols );
showColSums( A, Arows, Acols );
// cleanup
delete [] A;
}
else cout << "Could not get array data\n";
return 0;
}
// definitions
void readFile()// just looking
{
std::ifstream fin("arrData.txt");
int val=0, rows=0, cols=0, numItems=0;
while( fin.peek() != '\n' && fin >> val )
{
cout << val << ' ';
++numItems;
}
cols = numItems;// # of columns found
cout << '\n';
while( fin >> val )
{
++numItems;
cout << val << ' ';
if( numItems%cols == 0 ) cout << '\n';
}
rows = numItems/cols;
cout << "rows = " << rows << ", cols = " << cols << '\n';
}
// copies file data to array
int* readFile( const char* fname, int& rows, int& cols )// copies file data to array
{
std::ifstream fin( fname );
int val=0, numItems=0;
while( fin.peek() != '\n' && fin >> val ) ++numItems;
cols = numItems;// # of columns found
while( fin >> val ) ++numItems;// keep counting
// got data!
if( numItems > 0 )
{
rows = numItems/cols;
int *A = new int[rows*cols];
fin.close();
fin.open( fname );
// fin.seekg( 0, fin.beg );// I can't get the "right way" to work
int i=0;
while( i < numItems && fin >> A[i] )++i;
return A;
}
else// didn't get any data
cout << "data reading failed\n";
return nullptr;
}
void print( int* A, int rows, int cols )
{
if( !A ) return;
for( int r=0; r<rows; ++r )
{
cout << '\n';
for( int c=0; c<cols; ++c )
cout << A[r*cols + c] << ' ';
}
cout << '\n';
}
void showColSums( int* A, int rows, int cols )
{
if( !A ) return;
cout << "column sums\n";
for( int c=0; c<cols; ++c )
{
int colSum = 0;
for( int r=0; r<rows; ++r )
colSum += A[r*cols + c];
cout << colSum << ' ';
}
cout << '\n';
}
|