jeudi 5 décembre 2019

Reading matrix text file [closed]

Help! With how getline and other commands work in reading a text file line-by-line. I wish to read a text file using getline then convert it to integer (or type of number) to be used as values in my elements.

#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include "Vector.h"
using namespace std;

typedef unsigned int uint;

//Matrix class to handle basic linear algebra operations.
template<typename T>
class Matrix
{
    public:
        vector<vector<T> > elements;
        uint shape[2];

        // Constructors
        Matrix();
        Matrix(uint, uint);
        Matrix(vector<vector<T> >);
        Matrix(string);

        //Print vector elements.
        void print() const;

        //Print vector shape.
        void printshape() const;

        //Append a vector to the last row.
        void push_back(vector<T>);

        //Check if matrix has same shape to other matrix.
        bool has_same_shape(Matrix<T>&) const;

        //Save matrix to a text file with string filename as parameter.
        void savetext(string) const;

        //Indexing operator that returns the row as a Vector class.
        vector<T> operator[] (uint);

        //Comparison operator.
        bool operator== (Matrix<T>&);

        //Matrix transpose.
        Matrix<T> transpose();

        //Destructor.
        ~Matrix();

};

// Constructor with txt filename as parameter. 
template<typename T> 
Matrix<T>::Matrix(string filename){
    #include <sstream>
    #include <string>
    T num_col = 0;
    T num_row = 0;
    double value;
    string line;
    uint i = 0;
    ifstream infile(filename);
    if(infile.is_open()){
        elements.emplace_back();
        num_row++;
/*
        elements.emplace_back();
        num_row++;
        while(getline(infile, value)){
            infile >> value;
            elements[i].push_back(value);
            num_col++;
            i++;
        }
        shape[0] = num_row;
        shape[1] = num_col;
*/
        while (getline(infile, line)){
            istringstream iss(line);
            while (iss >> value){
                elements[i].push_back(value);
                i++;
                num_col++;
            }
        }
        shape[0] = num_row;
        shape[1] = num_col;
    }
    else{
        cout << "File does not exists!" << endl;
        exit(0);
    }
    infile.close();
}

Sample text file:

1 2 3 4 5 6

7 8 9 10 11 12

13 14 15 16 17 18

or

1234 2345 3456 4567

1234 2345 3456 4567

Aucun commentaire:

Enregistrer un commentaire