I want to create a function read data of type integer or double from a text file and stores them in a 2-dimensional array. But the number of the data in the text file is unknown during the program execution. Therefore the size of the array is also unknown.
I have problems in reading the correct data value of type int and double and stores them in the array. I also can't determine the correct total of columns and rows for the array.
My data in the text file looks something like this:
11001101010101010
10101011111111111
00111011111100001
Currently,the data in my file consists of 32 rows and 34 columns, and I tried using vector as shown below. But the program didn't return the correct rows and columns values. It read the row as 28 and column as 1 only. Also the program seem didn't able to read the data value into the vector as array data. No data is displayed on screen.
Code:
#include <fstream> // for ifstream
#include <iostream> // for cout
#include <vector> // for vector
#include <iomanip> // for setw
#include <string> // for string
#include <sstream> // for stringstream
template <typename T>
void ReadMatrix(const char * fname , std::vector< std::vector<T> > & matrix)
{
using namespace std;
T value;
string line;
ifstream in(fname);
vector<T> v;
while (getline(in,line))
{
v.clear();
stringstream ss(line);
while (ss >> value)
v.push_back(value);
matrix.push_back(v);
}
}
template <typename T>
void PrintMatrix(std::ostream & out, const T & matrix)
{
for (int i=0; i<matrix.size(); ++i)
{
for (int j=0; j<matrix[i].size(); ++j)
{
out << std::setw(10) << matrix[i][j];
}
out << "\n";
}
}
typedef std::vector< std::vector<int> > IMATRIX;
int main()
{
IMATRIX imatrix;
// optionally reserve to make reading in a little more efficient
ReadMatrix("test.txt",imatrix);
PrintMatrix(std::cout,imatrix);
return 0;
}
Later, I need to scan each row of data for 0s and stores them in text file. then I access the text file to normalize all 0s by rows. Therefore I need to save the information about the location of the 0s(which rows and columns). After the normalization, I need to replace the 0s in the later text file with the new value at the correct location. How to save the location value(rows and pixels) and corresponds them with their new normalized value?
Thanks in advance.