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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using std::cout;
using std::vector;
void readFile( const char* fname );// just looking
bool readFile( const char* fname, vector<int>& A, int& rows, int& cols );// copies file data to array
void print( const vector<int>& A, int cols );
void showColSums( const vector<int>& A, int cols );
void showRowSums( const vector<int>& A, int rows );
int main()
{
int Arows=0, Acols=0;
vector<int> A;
readFile("MatHW1.txt");
if( readFile( "MatHW1.txt", A, Arows, Acols ) )
{
print( A, Acols );
print( A, Arows );
showColSums( A, Acols );
showRowSums( A, Arows );
}
else cout << "Could not get array data\n";
return 0;
}
void readFile( const char* fname )// just looking
{
std::ifstream fin( fname );
int val=0, rows=0, cols=0, numItems=0;
std::stringstream ss;
std::string temp;
getline( fin, temp );
ss << temp;
while( ss >> 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 vector
bool readFile( const char* fname, vector<int>& A, int& rows, int& cols )// copies file data to array
{
std::ifstream fin( fname );
int val=0, numItems=0;
A.clear();
std::stringstream ss;
std::string temp;
getline( fin, temp );
ss << temp;
while( ss >> val ){ ++numItems; A.push_back(val); }
cols = numItems;// # of columns found
while( fin >> val ){ ++numItems; A.push_back(val); }// keep counting
// got data!
if( A.size() > 0 )
{
rows = numItems/cols;
return true;
}
else// didn't get any data
cout << "data reading failed\n";
return false;
}
void print( const vector<int>& A, int cols)
{
if( A.size() < (unsigned int)cols ) return;
cout << '\n';
for( size_t i=0; i<A.size(); ++i )
{
cout << A[i] << ' ';
if( (i+1)%cols == 0 ) cout << '\n';
}
cout << '\n';
}
void showColSums( const vector<int>& A, int cols )
{
if( A.size() < (unsigned int)cols ) return;
cout << "column sums\n";
int rows = A.size()/cols;
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';
}
void showRowSums(const vector<int>& A, int rows )
{
if( A.size() < (unsigned int)rows ) return;
cout << "row sums\n";
int cols = A.size()/rows;
for (int c=0; c<cols; ++c )
{
int rowSum = 0;
for (int r=0; r<rows; ++r )
rowSum += A[r*rows + c];
cout << rowSum << ' ';
}
cout << '\n';
}
|