views:

205

answers:

1

I'm trying to fill a pointer matrix with values from a text file. It's a double pointer to a simple struct with 2 ints, time and tons.

void get_changes(change** &c){
    ifstream file("change_data_time.prn");  //data file, time only, size is the same as tons
    string line, var;                   //string placeholders for the getlines
    int i, j;                           // count variables
    int count=0;
    while(getline(file, line))
        count++;                    //counting matrix size (matrix is square)

    c = new change *[count];    //resize pointers with matrix size
    for(i=0; i<count; i++)
        c[i] = new change[count];

    file.clear();
    file.close();
    file.open("change_data_time.prn");  //reset data stream to read values

    i = 0;  //reset counting variables
    j = 0;
    while(getline(file, line)){
        stringstream sline(line);           //getlines only read streams and output to strings
        while(getline(sline, var, '\t')){   //separate with tabs
            stringstream svar(var);
            svar >> c[i][j].time;       //BREAKS HERE
            j++;
        }
        i++;
    }
}

It breaks when i actually try to add the values to the pointer array and i can't understand why. It breaks on the first run of the while loops.

Thanks in advance for any suggestions.

+3  A: 

I would rewrite the code to get rid of the manual memory management around change** c.

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>

struct MaxtrixElement
{
    double time;
};

std::istream& operator >> (std::istream& in, MaxtrixElement& dest)
{
    double d;
    // error checking ommitted
    in >> d;
    dest.time = d;
    return in;
}

std::ostream& operator << (std::ostream& os, const MaxtrixElement& e)
{
    os << e.time;
    return os;
}

typedef std::vector<MaxtrixElement> Line;
typedef std::vector<Line> Matrix;

void foobar(std::istream& is, Matrix& dest)
{
    std::string ln;
    while(std::getline(is, ln))
    {
        std::stringstream lnStream(ln);
        Line l;
        std::copy(std::istream_iterator<MaxtrixElement>(lnStream),
                  std::istream_iterator<MaxtrixElement>(),
                  std::back_inserter(l));
        dest.push_back(l);
    }
}

int main()
{
    Matrix m;
    foobar(std::cin, m);
    for(Matrix::const_iterator it=m.begin(); it!=m.end(); ++it)
    {
        std::copy(it->begin(), it->end(), std::ostream_iterator<MaxtrixElement>(std::cout, ", "));
        std::cout << '\n';
    }
}
Rudi
Thanks for this, i'm going to give it a try. I just started learning C/C++ and still don't know my way around vectors, so I'll look into this.
jmclem
+1 - not only does this remove the need for memory management, but it also uses the STL beautifully to handle both input and output for the Matrix object. I need to write more code like this myself. :)
Talvalin