I've been struggling on this for about an hour now so I'm turning to the almighty entity that is the internet for assistance.
I'm trying to write a program that will A) read a matrix from a txt file in the following format where the first number is the columns (4) and the second number is the rows(3) in the matrix. And each row of numbers corresponds to a row in the matrix.
4 3
1 2 3 4
0 1 2 7
4 1 9 2
and B) calculate the number of ones in the matrix. So the above example would return 3. My code is below.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void count_ones(int matrix[][], int rows, int columns)
{
int count = 0;
for(int i = 0; i < rows; i++)
{
for( int j = 0; j < columns; j++)
{
if( matrix[i][j] == 1)
{ count++;}
}
}
cout << "There are " << count << " ones in this matrix.";
}
int main(int argc, char* argv[])
{
int rows, columns;
string file_name = argv[1];
ifstream reader("m1.txt");
reader >> columns;
reader >> rows;
int matrix[rows][columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
reader >> matrix[i][j];
}
}
cout << columns << " " << rows;
cout << endl;
for( int k = 0; k < rows; k++) {
for( int l = 0; l < columns; l++)
cout << matrix[k][l] << " ";
cout << endl;
reader.close();
count_ones(matrix, rows,columns);
return 0;
}
}
Right now I have two issues. The code i'm using to print the matrix I'm reading from the "m1.txt" file is only printing the first two lines and I have absolutely no clue what could be causing this but I'm guessing it has something to do with my ifstream reader.
4 3
1 2 3 4
Secondly, I'm getting a bunch of errors I don't understand when I try to pass my matrix to my count_ones function. I'm not very good with C++ so I would appreciate all the help I can get.
In a comment, you asked
Does anyone have a better way to pass the matrix to the count_ones method?
Don't use
int matrix[rows][columns];
This is not standard C++. It is supported by some compilers as an extension.
Use
std::vector<std::vector<int>> matrix;
You can initialize it with the correct sizes for rows and columns using
std::vector<std::vector<int>> matrix(rows, std::vector<int>(columns));
Change the declaration of count_ones
to accept a std::vector<std::vector<in>>
.
int count_ones(std::vector<std::vector<in>> const& matrix);
Update its implementation accordingly.
You can avoid the error of putting the closing }
in the wrong place by using helper functions to write the matrix to cout
.
std::ostream& operator<<(std::ostream& out, std::vector<int> const& row)
{
for ( int item : row )
out << item << " ";
return out;
}
std::ostream& operator<<(std::ostream& out, std::vector<std::vector<int>> const& matrix)
{
for ( auto const& row : matrix )
out << row << std::endl;
return out;
}
and then use
std::cout << matrix;
in main
.