I/O to/from a .txt file

I am having trouble reading from a .txt file i have already made in the format of:

2 3
1 2 3
4 5 6

I am trying to extract the "2 3" row as dimensions to a Matrix.
The remaining numbers are the components of my matrix arranged as so.

I am wanting to make a function called matrixFromFile("m1.txt") that gets input of a file, here m1.txt, then return a matrix.


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
//this is my Matrix Header File
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
class Vector;

class Matrix {
public:
    Matrix (double a[], int n_row, int n_col);//Constructor
    Matrix ();//Default Constructor
    ~Matrix();//Deconstructor
    double value(int i, int j);//Gets a Value in a matrix in a certain spot
    Vector row(int i);//Gets a Single Row of the Matrix and returns a Vector
    int row();
    int col();
private:
    int r;//Rows
    int c;//Columns
    double * coms;//Components
};

#endif // MATRIX_H_INCLUDED


//this is my Matrix Class
#include "Matrix.h"
#include "Vector.h"

Matrix::Matrix (double a[], int n_row, int n_col)//Constructor
{
    r = n_row;
    c = n_col;
    coms = new double[r*c];
    for (int i=0; i<r*c; ++i)
        coms[i] = a[i];
}
Matrix::Matrix ()
{
    r = 2;
    c = 3;
    coms = new double[r*c];
    for (int i=0; i<r*c; ++i)
        coms[i] = 0;
}
Matrix::~Matrix() {delete [] coms;}//Deconstructor

double Matrix::value(int i, int j)
{
    return coms[(i-1)*c+j-1];
}

Vector Matrix::row(int i)
{
    double a[c];
    for (int j=0, t=(i-1)*c; j < c; ++j, ++t)
        a[j]=coms[t];
    return Vector(a,c);
}

int Matrix::row()
{
    return r;
}
int Matrix::col()
{
    return c;
}


//This is what i have so far:

Matrix matrixFromFile(std::ifstream infile)
{
  //load the text file and put it into a single string:
    std::ifstream in("m1.txt");
    std::stringstream buffer;
    buffer << in.rdbuf();
    std::string test = buffer.str();
    std::cout << test << std::endl << std::endl;
    Vector c = extractVectorFromString(test);
    Matrix returnthis;
    return returnthis;
}
//this is what extractVectorFromString is doing:
Vector extractVectorFromString(std::string line)
{
    std::stringstream ss(line);
    char ch;
    int dim;
    ss >> dim >> ch;// d [
    int i;

    double * vec = new double[dim];
    for (i=0; i<dim; ++i) // ...,dn]
        ss >> vec[i] >> ch;

    if (ch != ']') // dim under
        throw "Dimension error!";

    if (!ss.good()) // dim over
        throw "Dimension error!";

    Vector v(vec,dim);
    delete [] vec;
    return v;
}
Last edited on
Topic archived. No new replies allowed.