A student looking for some guidance...
This is a class assignment with the instructions:
Re-write your program, List of Chores, using a unique_ptr
object as your data member. You should store a dynamic array in the unique_ptr
object. Use this array for storing, retrieving, deleting and updating chores.
I am trying to learn more about using the unique_ptr
object so I may create the constructor which is supposed to initialize the list. A text file has the list and the constructor should store that list into an array. I am trying to work around the error "Access violation reading location." In the original program, I created a temporary dynamic array with a larger capacity and copied the list into that array. There's a list of 10 chores in the text file. Here is that code:
In Header:
private:
/* var to keep len of list */
int len = 0;
int max = 9;
/* add appropriate data structure to store list */
string *arr = new string[max];
In .cpp:
/* reads the file line by line and initializes list */
ListOfChores::ListOfChores(string fileName){
ifstream file(fileName, ifstream::in);
string line;
if (file.is_open()) //Checking if the file can be opened
{
while (getline(file, line)) // Gets a single line
{
if (len >= max)
{
string *narr = new string[max + 10]; // New, larger array
for (int i = 0; i < max; i++)
{
narr[i] = arr[i]; // Copies line
}
delete[] arr; // Clears
arr = narr; // Copies
max += 1; // Growth
}
arr[len] = line; // Store a line in the array
len++; // Increases length by 1
}
file.close(); // Closes file
}
else cout << "Unable to open file" << endl;
}
And to show that I have been working on this and am not a lazy student...
New program attempt header:
private:
/* var to keep len of list */
int len = 0;
int max = 9;
/* add appropriate data structure to store list */
string *arr = new string[max]; // Primary array
string *narr = new string[max]; // New array
New program .cpp:
/* reads the file line by line and initializes list */
ListOfChores::ListOfChores(string fileName) {
unique_ptr<string[]> arr(new string[max]); // Unique pointer initialization
ifstream file(fileName, ifstream::in);
string line = " ";
if (file.is_open()) //Checking if the file can be opened
{
while (getline(file, line)) // Gets lines from file
{
if (len >= max)
{
max++; // Growth
unique_ptr<string[]> narr(new string[max]); // New unique pointer
narr = move(arr);// narr owns the object
narr[max] = line; // Store a line in the array
len++; // Increases length by 1
arr = move(narr); // arr owns the object
}
else
{
arr[len] = line; // Store a line in the array
len++; // Increases length by 1
}
}
file.close(); // Closes file
}
else cout << "Unable to open file" << endl;
}