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

Discussion in 'C++' started by bluekite2000@gmail.com, Sep 14, 2005.

  1. Guest

    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?
    , Sep 14, 2005
    #1
    1. Advertising

  2. <> wrote in message
    news:...
    >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
    =?iso-8859-1?Q?Ali_=C7ehreli?=, Sep 14, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dave
    Replies:
    3
    Views:
    547
    John Harrison
    Feb 28, 2004
  2. John Smith
    Replies:
    2
    Views:
    417
    Ivan Vecerina
    Oct 6, 2004
  3. Replies:
    2
    Views:
    535
  4. Jaco Naude
    Replies:
    1
    Views:
    939
    Jaco Naude
    Jan 14, 2010
  5. zhong huang

    read matrix file into 2d array

    zhong huang, Nov 21, 2003, in forum: Perl Misc
    Replies:
    7
    Views:
    1,232
    Uri Guttman
    Nov 22, 2003
Loading...

Share This Page