Reading a .dat file

Hi there,
I am finding trouble with the following action. I have written a long code, so as to solve a linear system of equations, but sometimes (it seems almost randomly) the console suddenly stops working (this is, it compiles but it does not reach the end of the programme, since it must have found something irregular). So, in order to correct that, I have created a new code, adding one by one all the parts of the first one, and compiling lots of times, and I think I have found where the problem comes from - the following action.
The purpose of this action is to read a vector, which comes from a .dat file (the first line is the dimension of the vector, followed by the components).
Do you find something that could make my code to break?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

  typedef vector<double> vdouble; //A class I create to be able to work with actions, with non-constant dimension


  void read_vector(vdouble& b, int n){ //n is the dimension of the vector, given on the action
	FILE *file3;
	vdouble m(n);
	file3=fopen("vector_b.dat", "r");
	for (int i=0; i<n+1; i++){
		fscanf(file3, "%lf \n", &(m[i]));
	}
	for (int i=0; i<n; i++){
		b[i]=m[i+1];
	}
	cout<<"Now I am writing the vector so as to be sure it is right."<<endl;
	for (int i=0; i<n; i++){
		cout<<b[i]<<" ";
	}
}


Thanks,
Somek
Last edited on
In the first loop m[i] is out of bounds when i=n.

In the second loop m[i+1] is out of bounds when i=n-1.

If b.size() is less than n you also have a problem with b[i] in the second and third loop.
Last edited on
Topic archived. No new replies allowed.