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
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//======================================================================
bool readSomething( istream &in, string &item )
{
return (bool)getline( in >> ws, item, ';' );
}
//======================================================================
template<typename T>
char parseSomething( const string &item, string &name, T &S, vector<T> &V, vector< vector<T> > &M )
{
char ctype, c;
S = 0;
V.clear();
M.clear();
// Get the type
int n = count( item.begin(), item.end(), '[' );
if ( n == 0 ) ctype = 's'; // scalar
else if ( n == 1 ) ctype = 'v'; // vector
else ctype = 'm'; // matrix
stringstream ss( item );
getline( ss, name, '=' );
switch ( ctype )
{
case 's':
ss >> S;
break;
case 'v':
ss >> c;
for ( T i; ss >> i; ) V.push_back( i );
break;
case 'm':
ss >> c;
for ( int r = 0; r < n - 1; r++ )
{
ss >> c;
string row;
getline( ss, row, ']' );
ss >> c;
stringstream srow( row );
for ( T i; srow >> i; ) V.push_back( i );
M.push_back( V );
V.clear();
}
}
return ctype;
}
//======================================================================
template<typename T>
void printMatrix( const vector< vector<T> > &M, int width )
{
for ( auto &row : M )
{
for ( auto e : row ) cout << setw( width ) << e << ' ';
cout << '\n';
}
}
//======================================================================
int main()
{
ifstream in( "data.txt" );
double S;
vector<double> V;
vector< vector<double> > M;
string item, name;
for ( int thing = 0; thing < 3; thing++ )
{
readSomething( in, item );
parseSomething<double>( item, name, S, V, M );
cout << "Read " << name << '\n';
}
// Assuming the given data file then the last thing read is the matrix F; either use M or make a copy
auto F = M;
F[2][2] = 100; // or whatever
// Check
cout << "\nPrinting modified matrix:\n";
printMatrix( F, 3 );
}
|