Returning a string array

I have a class BookType and it has authors in an array(4 maximum) how can i set the authors and return the array to print it out?


class BookType{

public:

/// method GetAuthors to return an array of authors
string GetAuthors() const;
/// method SetNrOfAuth to set the nr of authors
void SetNrOfAuth(int nr);


private:
string authors[4];
int nrOfAuthors;

};

#include "BookType.h"
int main (int argc, char * const argv[]) {

BookType b[100];
int nr;

cout << "enter nr of authors, max 4 authors" << endl;
cin >> nr;
b[0].SetNrOfAuth(nr);
string a[nr];

for (int i=0; i<nr; i++) {
cout << "enter author nr "<< i+1 <<endl;
cin >> a[i];
}

b[0].SetAuthor(a);


//How do i print out the authors to the screen?
for (int x=0; x<b[0].GetNrOfAuth(); x++) {
cout << //????
}


return 0;
}

I have supplied a main, to represent what i want to do, can someone help me?

First this doesn't makes sense, IMO your class name "BookType" does not have/do what its name imply!?
You could try to store your authors names in a vector of string's, and when you add author to the vector you just clamp it to your max (4).
Something like:
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class BookType
{
public:

	BookType() : currentNumOfAuthors(0), maxNumOfAuthors(4) {}

	void AddAuthor(const string& name)
	{
		if(authors.size() < maxNumOfAuthors)
		{
			authors.push_back(name);
			++currentNumOfAuthors;
		}
	}

	vector<string>& GetAuthors() { return authors; }


private:

	int currentNumOfAuthors;
	const int maxNumOfAuthors;
	vector<string> authors;
};


int main () 
{
	const int numBookTypes = 3;

	BookType b[numBookTypes];

	b[0].AddAuthor("BookType0AuthorName1");
	b[0].AddAuthor("BookType0AuthorName2");
	b[0].AddAuthor("BookType0AuthorName3");

	b[1].AddAuthor("BookType1AuthorName1");
	b[1].AddAuthor("BookType1AuthorName2");
	b[1].AddAuthor("BookType1AuthorName3");
	b[1].AddAuthor("BookType1AuthorName4");

	b[2].AddAuthor("BookType2AuthorName1");
	b[2].AddAuthor("BookType2AuthorName2");

	for(int i = 0; i < numBookTypes; ++i)
	{
		vector<string> currentBTAuthors = b[i].GetAuthors();
		for(int j = 0; j < currentBTAuthors.size(); ++j)
		{
			cout << "BookType[" << i << "], author[" << j << "] is " << currentBTAuthors[j].c_str() << endl;
		}
	}

	cout << "Press enter to exit...";
	cin.get();
	return 0;
}


EDIT: I just sow an unnecessary variable "currentNumOfAuthors", as we can use vector::size() for num. of authors for current booktype. Just remove it.
Last edited on
Thank you so much for your time, i did not include all variables and methods, probably why i didnt make any sense, but you answered my question very good thank you
Topic archived. No new replies allowed.