/* arrayOfStructsContainingArrays.cpp Demonstrate the use of arrays that hold struct objects that hold arrays John Sterling CS1124 Polytechnic University */ #include #include #include #include using namespace std; const int BREED_MAX = 20; // Maximum number of breeds that can be stored for a Dog. // This should be a static const int inside the Dog struct, // but we haven't covered that. struct Dog { string name; // The name of the dog string breed[BREED_MAX]; // A dog may be a combination of several breeds int countOfBreeds; // How many breeds for this dog? int age; // Age of the dog. (Probably better to use date of birth). }; void displayDog(const Dog&); int fillKennel(ifstream&, Dog[], int); int main() { const int KENNEL_SIZE = 10; Dog kennel[KENNEL_SIZE]; //ifstream ifs("dogs.txt"); ifstream ifs; ifs.open("dogs.txt"); if (!ifs) { // equivalent to: if (ifs.fail()) { cerr << "Idiot! I can't open the file!\n"; exit(17); } int count = fillKennel(ifs, kennel, KENNEL_SIZE); cout << "Total number of dogs read in: " << count << endl; // Display the dogs that were read in for (int i = 0; i < count; ++i) displayDog(kennel[i]); } // fillKennel is passed a stream to read descriptions of dogs from, // an array of dogs to fill // the size of the array // It returns the number of dogs that have been read into the array. // At most sizeOfDogs number of Dogs will be read from the stream. // Returns the number of Dogs placed in the array. // Each line of the file describes a single dog. // Each line consists of: // name age breed1 breed2 ... int fillKennel(ifstream& dogStream, Dog myDogs[], int sizeOfDogs) { int dogIndex = 0; // Fill the array. // Use the && operator's "short circuiting" // to prevent more than sizeOfDogs number of Dogs to be read while (dogIndex < sizeOfDogs && dogStream >> myDogs[dogIndex].name) { dogStream >> myDogs[dogIndex].age; string breeds; getline(dogStream, breeds); // Get the remainder of the line containing thebreeds istringstream iss(breeds); // Set up a stream to read the breeds from int breedIndex(0); // Index for filling the breeds array // Fill the Dog's array of breeds. At most BREED_MAX breeds from the line // will be used. Any more than that will be ignored. while( breedIndex < BREED_MAX && iss >> myDogs[dogIndex].breed[breedIndex] ) { ++breedIndex; } myDogs[dogIndex].countOfBreeds = breedIndex; ++dogIndex; } return dogIndex; } // Display a dog void displayDog(const Dog& d) { cout << "Name: " << d.name << "; Age: " << d.age << "; Breeds: "; // Display all but the last breed followed by ", ". for (int i = 0; i < d.countOfBreeds-1; ++i) cout << d.breed[i] << ", "; // Display the last breed followed by a newline. if (d.countOfBreeds > 0) cout << d.breed[d.countOfBreeds-1] << endl; }