void matrix::read_file(char* filename)
{
ifstream i_f;
matrix c;
string o;
int *v,t(0),x(0),y(0),z(0);
while(!i_f.eof())
{
getline(i_f,o);
//this o string is not input correctly
t = o.length();
v = newint[t];
for(z=0;z<=t;z++)
{
*(v+z) = int(o[z])-48;
}
y++;
}
c.allocate(t,y);
for(z=0;z<(x*y);z++)
{
cout<<"putting\n";
c.set_i(*(v+z),z);
}
i_f.close();
}
allocate() allocates the memory for the 2 dimensional array to be stored.It works correctly.
set_i(<value>,<location>)is for putting the individual elements of the array into position.It also works correctly.
That is because EOF flag is not set until after the read fails. So doing it your way will execute the loop with invalid data. But if you test the return of getline() in the while condition you can guarantee that the loop only executes if the read was successful.
void matrix::read_file(char* filename)
{
ifstream i_f( "filename.txt" ); // open the file
matrix c; // this stores the result and is destroyed at the end of the function
string o;
int *v,t(0),x(0),y(0),z(0); // generally, declare locals at late as possible
while(!i_f.eof()) // as Galik said, move getline here
{
getline(i_f,o);
//this o string is not input correctly
t = o.length(); // why?
v = newint[t];
for(z=0;z<=t;z++) // this goes 1 element beyond the space allocated for v
{
*(v+z) = int(o[z])-48; // how about: v[z] = o[z] - '0';
}
y++; // counting lines?
} // v was the "row" but is being leaked each iteration
c.allocate(t,y); // t is the length of the last line, y is the total number of lines
for(z=0;z<(x*y);z++)
{
cout<<"putting\n";
c.set_i(*(v+z),z); // what?
}
i_f.close();
}
1.Why? because I put a cout<<o<<"Here"; there ; but nothing except the Here is printed
2.I already put the getline there.Would I have to put it within again?It is becoming confusing
3.If it went 1 element beyond, a segmentation fault would appear.//I use linux, it does show segmentation faults at runtime
4.What?set_i(..........) puts an individual element of the array inside an int * value declared within the class.
the allocate function dynamically allocates x*y spaces to value.
The problem is that reading the file like this -> getline(i_f,o) also puts the tab characters in your string. This is something you don't want. Why don't you try doing it using the >> operator? And in order to know the size of the matrix, you can just store it in the file before the actual matrix data.