string* Problem

I have a jar of biscuits and every biscuits are words. I have to put and take biscuits. The putting i know how to make it but with the taking i have a problem.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Jar
{

private:
    string *biscuits;
    int amount;
    int jar_volume = 10;

public:


         void Take(string cookie)
    {
        if(amount == 0)
        {
            cout << "You have eaten all the cookies. Go and buy more!!!!" << endl;
            return;
        }
        if(amount == jar_volume / 2)
        {
            string *resize = new string[jar_volume / 2];
            for(int i = this->amount; i > 0; i--)
                resize[i] = this->biscuits[i];

            this->jar_volume = this->jar_volume / 2;
            delete this->biscuits;
            this->biscuits = resize;

        }
        this->biscuits[amount--] = cookie;

    }
   int Amount()
    {

        return this->amount;
    }


    int JarVolume()
    {

        return this->jar_volume;

    }

        ~Jar()
    {
        delete this->biscuits;

    }
};

int main()
{
        Jar p;

    cout << "How many cookies do you want to take: ";
    int num_take_c;
    cin >> num_take_c;
    string take_word;

    for(int i = 0; i < num_take_c; ++i)
    {  
        getline(cin, take_word);
        p.Take(take_word);
        cout << "Taken " << take_word << " cookie from the jar" << endl;
        cout << "Amount: " << p.Amount() << endl;
        cout << "Jar volume: " << p.JarVolume() << endl;
    }
    return 0;
}
Last edited on
Where is Jar's constructor? What unknown value will be stored in the member amount since you do not initialize it? Line 26 should use delete[] instead of delete. Why does line 30 have this->biscuits[amount--] = cookie;? Should you be putting a cookie into the jar during the Take method?
How can you test the Take method without having cookies in the jar? You should write the Put method first and test that.
Topic archived. No new replies allowed.