/****************************************************************************************** ex4.cpp Working our way to dynamic criteria Using our tally function with LOTS of states ******************************************************************************************/ #include <iostream> #include <string> #include <fstream> using namespace std; // class definition class person { public: string first; string last; string state; }; // prototypes void readFile(string filename, person [], const int maximum, int& size); int TallyByState(string token, person [], const int size); // MAIN! void main() { int count=0; const int maxsize=100; person census[maxsize]; string filename; cout << "Enter the file to read: "; cin >> filename; readFile(filename, census, maxsize, count); cout.precision(0); cout.setf(ios::fixed); int countDC = TallyByState("DC", census, count); int countMA = TallyByState("MA", census, count); int countNY = TallyByState("NY", census, count); int countNJ = TallyByState("NJ", census, count); int countOther = count - countDC - countMA - countNY - countNJ; cout << countDC << " records from Washington, D.C." << endl << countMA << " records from Massachusetts." << endl << countNY << " records from New York." << endl << countNJ << " records from New Jersey." << endl << countOther << " records from somewhere else." << endl << endl; float percentDC = (float)countDC/count; float percentMA = (float)countMA/count; float percentNY = (float)countNY/count; float percentNJ = (float)countNJ/count; float percentOther = 1 - percentDC - percentMA - percentNY - percentNJ; cout << percentDC*100 << "% of records from Washington, D.C." << endl << percentMA*100 << "% of records from Massachusetts." << endl << percentNY*100 << "% of records from New York." << endl << percentNJ*100 << "% of records from New Jersey." << endl << percentOther*100 << "% of records from somewhere else." << endl; } //------- return the count of records where state matches the token ------ int TallyByState(string token, person list[], const int size) { int count = 0; for (int i = 0; i < size; i++) if (list[i].state == token) count++; return count; } //------- fill each person in the list from a file ------ void readFile(string filename, person people[], const int maximum, int& size) { ifstream fin(filename.c_str()); for (int i=0; i < maximum; i++) { if(fin >> people[i].first >> people[i].last >> people[i].state) size++; } }