/*******************************************************************************************
08P.cpp
read data into an array of objects, display them and do some calculations on them
*******************************************************************************************/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class soldier
{
public:
string first;
string last;
string rank;
};
//prototypes
void readFrom(string file, soldier list[], const int size, int& count);
void showList(soldier [], const int size);
int countPrivates(soldier [], const int size);
void main()
{
const int MaxSize = 100;
soldier volunteers[MaxSize];
int count = 0;
string filename;
cout << "What is the file to read: ";
cin >> filename;
readFrom(filename, volunteers, MaxSize, count);
showList(volunteers, count);
cout << "-----------------------" << endl
<< "Privates: " << countPrivates(volunteers, count) << endl;
return;
}
int countPrivates(soldier list[], const int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
if (list[i].rank == "Private")
sum++;
return sum;
}
void showList(soldier list[], const int count)
{
for (int i = 0; i < count; i++)
{
cout << list[i].last << ", " << list[i].first
<< " (" << list[i].rank << ")" << endl;
}
return;
}
void readFrom(string file, soldier list[], const int size, int& count)
{
ifstream fin(file.c_str());
for (int i = 0; i < size; i++)
{
if(fin >> list[i].rank >> list[i].first >> list[i].last)
count++;
else
break;
}
return;
}