Solution


/* name:    task3.cxx
   author:  Leo Liberti
*/

#include <iostream>
#include <fstream>
#include <cmath>
int main(int argc, char** argv) {
  using namespace std;
  if (argc < 3) {
    cerr << "error: need filename containing m x n matrix, and the integer n"
         << "\n      on the command line" << endl;
    exit(1);
  }
  
  ifstream ifs(argv[1]);
  if (!ifs) {
    cerr << "error: cannot open file " << argv[1] << endl;
    exit(2);
  }
  
  int n = atoi(argv[2]);

  double t;
  int i = 1;
  char c;
  bool firstTerm = true;
  while(true) {
    ifs.get(c);
    ifs >> t;
    if (ifs.eof()) {
      break;
    }
    if (t != 0) {
      if (t < 0) {
        if (firstTerm) {
          cout << "-";
        } else {
          cout << " - ";
        }
        if (fabs(t) != 1) {
          cout << fabs(t) << "*";
        }
        cout << "x[" << i << "]";
      } else {
        if (!firstTerm) {
          cout << " + ";
        }
        if (t != 1) {
          cout << t << "*";
        }
        cout << "x[" << i << "]";
      } 
    }
    firstTerm = false;
    i++;
    if (i > n) {
      i = 1;
      firstTerm = true;
      cout << " = 0" << endl;
    }
  }
  return 0;
}



Leo Liberti 2008-01-12