int loadCarts(string filename,SnackCart *&carts) {
carts = new SnackCart;
ifstream dataFile(filename.c_str());
int count = 0;
string type;
getline(dataFile,type);
while (!dataFile.eof()) {
if (type == "Snackcart"){
string owner;
getline(dataFile,owner);
if (owner == "") {
break; // stop read if reach end of file
} else {
carts[count].setOwner(owner);
string location;
getline(dataFile,location);
carts[count].setLocation(location);
carts[count].clearMeals();
bool moreMeals = true;
while (moreMeals) {
string meal;
getline(dataFile,meal);
if (meal == "#") {
moreMeals = false;
} else {
string numStr;
getline(dataFile,numStr);
float num = (float) atof(numStr.c_str());
string ratingStr;
getline(dataFile,ratingStr);
carts[count].addMeal(meal,num,ratingStr);
}
}
}
}
++count;
}
dataFile.close();
i have the above function and i know what exactly is wrong with it. this function is used to read snackcarts from a text file. the problem is since i dont know how many snackcarts are present in the text file, i end up with errors. carts is dynamically declared but at the moment it can take only one set of values for one cart. how do i set the size of the array in this case? im guessing i can use vectors but even after reading up on it im still unsure of how to implement them.
i want to know how to resize the vector and in such a way that the array is only equal to the size it needs to be. how about if i keep a count value that increments itself as the vector is filled and then the final count value i use to resize the vector. will that do the trick?
You should start with an empty vector (vector containing 0 elements) and use the push_back() method to
add elements to it. In this way, when you are done, the vector will be exactly as large as you wanted it.
no a vector is a template type meaning that for each input type there is created a version of the vector template. so your std::vector<SnackCart> is not a real type and can be treated like you would any normal stack variable.
There is now a copy of thisCart in carts... the internal handling of memory by the vector is not something you need to consider or understand in order to use it; however in time I would say you'll need to understand how it manages itself internally to make usage of it more efficient.