Hi guys, I have a program that makes a txt, and I am trying to read the contents from that txt and put it into a vector.
The first line in the file is MP-PER-T 300, with 300 being the numbers that are stored in the file.
from the second to the last line there are numbers (int). They are separated by a \n.
The first 7 lines
1 2 3 4 5 6 7
|
MP-PER-T 300
143
280
231
214
261
187
|
Honestly, I do not know how to "recognise" the first line (that contains the numbers of numbers that there are in the file), so I just count the bytes the file has, -10 (the number of characters in the first line) divided by 4 (size of an int).
Then, I make a vector with that information, I go back to the beginning of the file, get the first line out of the way, and start reading and storing in the vector.
But when printing it to check if it is right, it just prints 0's until it reaches a segfault. I have bolded the while that is giving me problems.
My function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
void permutacion::LeerPermutacion (const char file[]) {
char *s=0;
s= new char[20];
int tam, num,i=0;
ifstream fi(file);
if (!file){
cerr << "Error abriendo el fichero" << endl;
exit (1);
}
fi.seekg(0, ios::end); // Ir al final del fichero
tam = (fi.tellg());
tam= tam-10;
num = tam / sizeof(int); // contamos cuantos numeros hay
fi.seekg(0,ios::beg); // ir al principio del fichero
crear(num);
fi.getline(s, 15);
while (fi >> vector[i]) { // se queda en el bucle infinitamente
i++;
cout << vector[i];
}
fi.close();
}
|
1 2 3 4 5 6
|
void permutacion::crear(int num ) {
if (vector!=0) {
delete [] vector;
}
vector=new int[num];
}
|