This code is taken off a bigger project, but essentially there's a vector of type Script (my class) called Scr, and when I try to read data from a .txt into it, it crashes because the size is wrong at some point, i'm not sure.
bool Game::loadScript()
{
//This loads all the data from a .txt
std::ifstream scrStream ("script.txt");
if (scrStream.is_open())
{
unsignedlonglong lines = 0;
if (scrStream.good())
{
//Parse through .txt and see how many lines there are
// and read data into every object
int k = 2, j = 0;
/////////////////THIS PART////////////////////////////
do
{
std :: cout << k << " " << j << " ";
Scr.resize(k);
std::cout << Scr.size() <<std::endl;
scriptSize = k;
k++;
j++;
}
while(std::getline(scrStream, Scr[j].action));
/////////////////////THIS PART//////////////////////////////////
std::cout << "Script succesfully loaded!\n\nScript has "
<< lines << " / " << scriptSize << " lines filled.\n";
return 1;
}
scrStream.close();
}
else
{
//Checks for error when opening file
std::cout << "Unable to open file!\n";
return 0;
}
}
While I have no solution for your problem, but I wanted to point out something regarding the resize method you are using so freely in your code. This is equivalently what you are doing:
type *Src; // the underlying implementation of vector
do
{
std :: cout << k << " " << j << " ";
/* Scr.resize(k) begin */
type *ptr = new type[k];
// copy everything from Src to ptr and delete that heap allocated memory
type *cursor = &ptr[0];
for (auto item : Src)
*cursor++ = item;
delete Src;
// Assign Src to new address
Src = ptr
/* Scr.resize(k) end */
std::cout << Scr.size() <<std::endl;
scriptSize = k;
k++;
j++;
} while(std::getline(scrStream, Scr[j].action));
An alternative will be to use the push_back method exposed by the vector class or alternatively reserve memory for your vector so that memory allocations are not as frequent.
This is of course if efficiency is a concern of yours for this application, otherwise you can just ignore the above and continue with the implementation you have
Well, the plan is to open a file of unknown size and keep filling the vector as I go along in the file line by line, until we reach end of file.
I'm not sure what you mean , but shouldn't the vector size be in this case 'k', that increases by 1 every time? The problem is that the program runs, gets to the vector size of 2 and then crashes. (AND I HAVE _NO_ IDEA WHY). How can 2 iterations work perfectly fine and the 3rd one fail?