Guide about how to read a txt from a class

Hello! I'm trying to define a class call matrix who reads a txt with the data but I'm having problems with the lecture part. I'm posting the code that I have writen so far and the txt that I'm trying to read, hope someone can guide about this!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>

class Matrix{
public:
    Matrix() {};
    Matrix(std::string a) {data.open(a);};

    //here tried to use getline on data but it didn't work and run out of ideas


private:
    std::string path,line;
    unsigned int row_size,col_size;
    std::ifstream data; 


};


int main(){
    Matrix A("MatrixA");

}




Here is the MatrixA.txt:
Dim:
3 3
Val:
1 2 3
4 5 6
9 5 1
A couple of problems, first I don't recommend having the class open the file especially in the class constructor. A constructor should be defined to "never" fail, opening a file fails quite often so do this operation separately where the error can be safely reported and handled.

Next where are you going to store the values in the file, and where are you actually trying to read the file? Remember that in C++ array sizes must be either compile time constants or you need to use a container like std::vector or use dynamic memory.

Topic archived. No new replies allowed.