Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I have trouble reading/ allocating the matrix data (read from file) into my 1-d array. Suppose the matrix from the file () is as follows:
1 2
3 4


While I am trying to get the sum of its column, instead of getting values 4 for column 0 and 6 for column 1, my output is shown as 32598 and 1396448268, values that I cannot comprehend at all.

This is my current code:
C++
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream fin;

    fin.open("/Desktop/matrix.txt");

    int val = 0, rows = 0, cols = 0, numItems = 0;

    // Get the number of rows
    while( fin.peek() != '\n' && fin >> val )
    {
        //cout << "Value in Row is " << val << endl;
        numItems++;
    }
    cols = numItems;

    cout << '\n';

    // Get the number of columns
    while( fin >> val )
    {
        numItems++;
        //cout << "Value in Column is " << val << endl;

        if( numItems%cols == 0 ) 
        {
            cout << '\n';
        }
    }
    rows = numItems/cols;

    // Allocate it as 1-D array
    int arr[rows * cols];

    // read each value into the array
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            fin >> arr[i * cols + j];
        }
    }

    int sum = 0;
    for(int j = 0; j < cols; j++)
    {
        for(int i = 0; i < rows; i++)
        {
            sum += arr[i * cols + j];
        }
        cout << "Sum for column " << j << " = " << sum << endl;
    }
}



Am I doing it wrong somewhere in my above code?

What I have tried:

However if I remove the file-reading code portion and set a fixed value to my numRows and numCols, the output values will be correct but unfortunately having the fixed value is something not I had wanted as I will be reading in different files where the matrix can range from 2x2, 3x3, 2x4 etc..

Which is why I have implemented in the file-reading portion to get the number of columns and rows..
Posted
Updated 12-Apr-16 21:35pm
Comments
Sergey Alexandrovich Kryukov 13-Apr-16 1:07am    
Do you have a matrix class/struct? After all, are you going to develop in C++ or not?
Are all your matrices 2x2? What do you mean by "some of columns"? A column is a vector, so it could be a vector sum, and you are talking about some numbers...
—SA
xenas19 13-Apr-16 1:21am    
Yes I will be implementing in a matrix class, but currently I am not doing so because I had wanted to test it in main() to see if it is working before transferring the codes into the matrix class. As my matrix is via file input, I am trying to say that, the matrix in the file inputs comes in either 2x2, 3x3, 2x4 for example (different rows and columns)

As I wanted to access the values, I am allocating them into 1-D array without the use of 2-D array or vectors

I think it is time for you to stop guessing what your code is doing. It is time to see your code executing and ensuring that it does what you expect.

The debugger is your friend. It will show you what your code is really doing.
Follow the execution step by step, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Quote:
// Allocate it as 1-D array
int arr[rows * cols];
Last time I checked, this was not the way to dynamically allocate memory.
 
Share this answer
 
v2
Comments
xenas19 13-Apr-16 2:12am    
Thanks for pointing it out. It was a typo on my part. It should be "creation of 1-D array"
You are reading from the stream to detect the number of colums and rows. Once that is done, the stream position is at the end of the file. To read the data in afterwards you must change the stream read position back to the begin of the file using istream::seekg - C++ Reference[^]:
// Rewind input stream.
// This is missing in your code.
// NOTE: See [EDIT2] below for correct solution.
fin.seekg(0);

// read each value into the array
for(int i = 0; i < rows; i++)
{
    for(int j = 0; j < cols; j++)
    {
        fin >> arr[i * cols + j];
    }
}


[EDIT]
There is also a logical error in your code. You want to calculate the sum for each column but you do not clear the sum value for the next one:
C++
// Move this inside the loop
//int sum = 0;
for(int j = 0; j < cols; j++)
{
    // Move declaration of sum to this position to start with zero for each column
    int sum = 0;
    for(int i = 0; i < rows; i++)
    {
        sum += arr[i * cols + j];
    }
    cout << "Sum for column " << j << " = " << sum << endl;
}

[/EDIT]

[EDIT2]
Calling seekg() is not enough. When the complete file has been read, the failbit is set and must be cleared before seeking:
// Rewind input stream.
// This is missing in your code.
fin.clear();
fin.seekg(0);

[EDIT2]
 
Share this answer
 
v6
Comments
xenas19 13-Apr-16 4:03am    
hmm, I tried that but it is not working..
Jochen Arndt 13-Apr-16 4:11am    
Then it is time for debugging as suggested in solution 1.

If you have not done so far you may use also "poor man debugging" by adding lines printing the relevant values (detected numbers of rows and columns and the values stored in the array).

I just saw another error in your code and will update my solution.
xenas19 13-Apr-16 4:36am    
Okay then.. but can I ask - the portion of code that I wrote for '// read each value into the array' is that the right way for getting the values in the matrix(from the file)? I asked this because upon adding in a few print outs, it appears that my arr[i * cols + j] is the one that seems to be screwing things up..
Jochen Arndt 13-Apr-16 5:16am    
I tested it meanwhile and got a result which I can't explain:
The seekg() call will rewind but there is the fail bit set and even clearing that bit does not help.

Closing and re-opening the file instead helps:
//fin.seekg(0);
fin.close();
fin.open("/Desktop/matrix.txt");
xenas19 13-Apr-16 5:25am    
that is interesting to hear.. I did tried closing and opening again, however it still does not works.. The values generated are still some funky values that I can't comprehend

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900