Read file to decide size of array?

Hello guys ,

I'm having an assignment that needs me to code a program that reads a file that contains matrix and do operations between the matrix and cout it , the name of file will be obtained from user so basically the user just select an operation and type in the file name .

the contents of the file looks like this :


<matrix>
rows = 2
cols = 2

1 2
2 4
</matrix>

My idea in doing it is read the file , scan the contents for rows and cols and extract the number of them (which is 2 and 2 in this case) and put them into the size of array .

My problem now is I have no idea to scan the file and let it search certain contents instead of reading everything and store everything , and setting the number into the size of array , what I learnt so far from the books and lectures is constant array . Will someone shine some light on me ?

Also I'm using microsoft visual studio 2010 .

Thanks !
Last edited on
I'm not really getting what you are trying to say, but I can help a bit

Text file:
If you want to read into an int,long,char*,char,etc. use file>>
If you want to read including spaces, use file.getline(char* str,int size,char delim='\n');
If you want to read data but not store it, use file.ignore(int size=1,char delim=EOF);

Binary file:
If you have an int n and you want to read directly into it, do
file.read((char*)&n,sizeof(int));
similarly this is how you write an int to a file
file.write((char*)&n,sizeof(int));
If you want to directly jump to a specific point in the file use seekg() and seekp()

Details of all these functions is available on this site on the reference section.

I advise you to use binary file approach as then you would know how many bytes each object occupies. For eg. (assuming int on you computer is 4 bytes), reserve 1st 4 bytes for rows, next 4 bytes for columns and store contents of matrix in blocks of 4 bytes.

However, if you want to store file as text, you don't need to format it

Instead of
<matrix>
rows = 2
cols = 2

1 2
2 4
</matrix>


Do
2
2
1
2
2
4


For eg. if you want to add 2 matrices, open 2 files in read and 1 in write
mode (all files in binary mode, if using binary files). Read the number of columns(c) and rows(r) of both files and check if they are equal. If they are, then read one int from 1st file, another int from another file, add them and store them in the other file
Last edited on
The fact that you have <matrix></matrix> tells me that you are using some sort of XML file. Try using an xml parsing library. Although I would have expected it to look a little more like:
<matrix>
  <rows>2</rows>
  <cols>2</cols>
  <data>
    1 2 
    2 4
  </data>
</matrix>


If that's not what you are doing then try something like 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
25
26
27
28
29
30
std::ifstream fin("matrix.txt");
std::stringstream iss;
std::string line, word;
int m, n;
int* matrix;

getline(fin, line); // get rid of <matrix>
getline(fin, line); // rows;
iss.clear();
iss(line);
iss >> word; // gets rid of "rows"
iss >> word; // gets rid of "="
iss >> m; // stores the number of rows;

getline(fin, line); // columns;
iss.clear();
iss(line);
iss >> word; // gets rid of "columns"
iss >> word; // gets ride of "="
iss >> n; // stores the number of cols

matrix = new int[m*n];
for (int i = 0; i < m; i++)
{
    getline(fin, line);
    iss.clear;
    iss(line);
    for (int j = 0; j < n; j++)
        iss >> matrix[m * j + i];
}
Last edited on
By the way, I've always thought that the matrix file format described in this site is a good one since it's so easy to parse:

http://math.nist.gov/MatrixMarket/formats.html

It gives a file like this:
%%MatrixMarket matrix coordinate real general
%=================================================================================
%
% This ASCII file represents a sparse MxN matrix with L 
% nonzeros in the following Matrix Market format:
%
% +----------------------------------------------+
% |%%MatrixMarket matrix coordinate real general | <--- header line
% |%                                             | <--+
% |% comments                                    |    |-- 0 or more comment lines
% |%                                             | <--+         
% |    M  N  L                                   | <--- rows, columns, entries
% |    I1  J1  A(I1, J1)                         | <--+
% |    I2  J2  A(I2, J2)                         |    |
% |    I3  J3  A(I3, J3)                         |    |-- L lines
% |        . . .                                 |    |
% |    IL JL  A(IL, JL)                          | <--+
% +----------------------------------------------+   
%
% Indices are 1-based, i.e. A(1,1) is the first element.
%
%=================================================================================
  5  5  8
    1     1   1.000e+00
    2     2   1.050e+01
    3     3   1.500e-02
    1     4   6.000e+00
    4     2   2.505e+02
    4     4  -2.800e+02
    4     5   3.332e+01
    5     5   1.200e+01

and can be parsed like 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
///////////////////////////////
// get_matrix arguments:
// input : std::string filename... string containing the path to the file to be parsed
// output : double** matrix... NULL pointer which will output a pointer to the full matrix
// output : int m : returns the number of rows
// output : int n : returns the number of cols
//
// return value:
// 1 if the matrix pointer was not NULL (signifying a possible memory leak)
// 0 otherwise
//////////////////////////////////////////////
int get_matrix(std::string filename, double** matrix, int& m, int& n)
{
    int output = 0;
    std::ifstream fin(filename);
    std::stringstream iss;
    std::string Line;
    int L;

    if (matrix != 0) output = 1;

    do { // get rid of comment lines
        std::getline(fin, Line);
    } while (Line[0] == '%'); 

    // get matrix characteristics
    iss >> m >> n >> L;

    //size array and zero all elements
    matrix = new double*[m];
    for (int i = 0; i < m; i++)
    {
        matrix[i] = new double[n];
        for (int j = 0; j < n; j++)
            matrix[i][j] = 0.;
    }

    for (int i = 0; i < L && getline(fin, Line); i++)
    {
        int row, col;
        iss.clear();
        iss << Line;
        
        iss >> row >> col;
        iss >> matrix[row][col];
    }
}
Last edited on
@eklavya sharma 2

Uh that's not me that set the file like this , it was provided in this format and the program will prompt user for file name , thus the question I'm asking is how do I skip the useless part (bolded):


<matrix> rows = 2
cols = 2

1 2
2 4
</matrix>

and only extract the numbers ?

Maybe I'll read Stewbond's solution after I wake up , good night from Malaysia
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
void addition()
{
	string file1,file2;
	string line,word;
	istringstream get;

	 int **matrix;
	 int m ,n ; //m= rows , n=columns

	cout<<"You are using addition function now . \n";

	cout<<"Please enter the first file name that contains matrix :";
	getline(cin,file1);
	cout<<endl;

	cout<<"Please enter the second file name that contains matrix :";
	getline(cin,file2);
	cout<<endl;

	ifstream infile(file1,ios::in) ;
	
	if(!infile)
	 {
		 cerr<<"File 1 open error";
		 system("cls");
		 main();


	 }
	else 
		
	 {		
		 getline(infile,line);//getline for </matrix>
		 
		 getline(infile,line);//getline for rows
		
		 get.clear();//clear get stream;
						
		 get(line);

		 get>>word;

		 get>>word;

		 get>>m;

		 getline(infile,line);//getline for column

		 get(line);

		 get.clear();

		 get>>word; //read column
		 get>>word; //read =
		 get>>n;	//store column number

	 }


}


So this is the part where I should do addition of matrix , but in the part get(line) I have this error


IntelliSense: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type

What's wrong ?

I haven't do the matrix calculations yet , will work on it later .
Last edited on
bumping the thread
Topic archived. No new replies allowed.