overloading operator >> to read a text file into a Matrix

B

bluekite2000

I have
template <typename T>
inline std::istream& operator >> (std::istream& is, Matrix<T>& mIn)
{
int rows,cols;
is.clear();
is >> rows >> cols;
mIn._M=rows;
mIn._N=cols;
mIn.MatAlloc(rows,cols);//alllocate mem

for (int i=0;i<rows;i++)
for (int j=0;j<cols; j++)
if(is.good())
is >> mIn(i,j);

return is;
}
This works fine if i have a text file such as
2 3 //2 rows 3 cols
1 2 3
4 5 6

but if i have something like
2 3
1 2


I get a matrix M with the following data member
2 3
1 2 2
0 0 0

notice how M(0,1)==M(0,2) ==2 which i DONT want. Any idea?
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

I have
template <typename T>
inline std::istream& operator >> (std::istream& is, Matrix<T>& mIn)
{
int rows,cols;
is.clear();
is >> rows >> cols;
mIn._M=rows;
mIn._N=cols;
mIn.MatAlloc(rows,cols);//alllocate mem

for (int i=0;i<rows;i++)
for (int j=0;j<cols; j++)
if(is.good())
is >> mIn(i,j);

is will be "not good" only after attempting to read. Try this:

for (int i=0;i<rows;i++)
for (int j=0;j<cols; j++)
{
int value;
if (is >> value)
{
mIn(i, j) = value;
}
}

Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top