Help me solve this please

Jul 31, 2014 at 2:41pm
So here's my Code:

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
#include <iostream>
#include <string>
using namespace std;

class Cat
{
public:
	Cat();
	~Cat();
	int GetAge() const { return *itsage; } //inline
	void SetAge(int age){ *itsage = age; } //inline
	int GetWeight() const { return *itsweight; } //inline
	void SetWeight(int weight) { *itsweight = weight; } //inline
	string GetName() const { return *itsname; } //inline
	void SetName(string name) { *itsname = name; } //inline
private:
	int* itsage = nullptr;
	int* itsweight = nullptr;
	string* itsname = nullptr;
};
Cat::Cat()
{
	itsage = new int(12);
	itsweight = new int(4);
	itsname = new string;
}
Cat::~Cat()
{
	cout << "\nDestructor Called - Cleaning up memory.\n";
	delete itsage;
	delete itsweight;
	delete itsname;
}

int main()
{
	short int amountofkittens;
	cout << "How many kittens would you like to purchase?\n";
	cin >> amountofkittens;
	while (amountofkittens >= 10)
	{
		cout << "You cannot fit 10 or more kittens in your farm.\n";
		cout << "Try buying a smaller amount: ";
		cin >> amountofkittens;
	}
	Cat* kittens = new Cat[amountofkittens];

	delete[] kittens;
	kittens = nullptr;
	return 0;
}


So what i need to do is i need to give the user the ability to name their own kittens, i need to make another for loop which allows the user to name their kittens 1 after the other and then another for loop to display their names, how do i achieve this?

I know how to print out their names but i don't know how to let the user name each cat.
Last edited on Jul 31, 2014 at 2:43pm
Jul 31, 2014 at 2:59pm
You don't need those dynamic allocations. As it stands, you don't do anything about copies, so if your object was copied, you t application would eventually crash.

So Cat could be: ... I'll add an isNamed() method so we can check if it has a name yet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Cat
{
public:
	Cat();
	~Cat();
	int GetAge() const { return itsage; }
	void SetAge(int age) { itsage = age; }
	int GetWeight() const { return itsweight; }
	void SetWeight(int weight) { itsweight = weight; }
	string GetName() const { return itsname; }
	void SetName(string name) { itsname = name; }

        bool isNamed() const { return itsname.empty(); }

private:
	int itsage;
	int itsweight;
	string itsname;
};


Then you can add code like:
1
2
3
4
5
6
7
8
9
10
11
for (i = 0; i < amountofkittens; ++i)
{
    if (!kittens[i]->isNamed())
    {
        std::string name;
        cout << "This kitten doesn't have a name.  Please type one, or just press <Enter> to ignore" << std::endl;
        std::getline(std::cin, name);
        if (!name.empty())
            kittens[i]->setName(name);
    }
}
Jul 31, 2014 at 4:05pm
You have my thanks!
Topic archived. No new replies allowed.