#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void addStudent();
void readStudent(string [], int []);
void displayStudents(string [], int [], int);

int main()
{	
	const int SIZE = 5;
	string names[SIZE];
	int ages[SIZE];
	
	addStudent();
	readStudent(names, ages);
	//displayStudents(names, ages, SIZE);
	
	return 0;
}

void addStudent() {
	
	fstream outfile("students2.txt", ios::out);
	string name;
	int age;
	char answer;
	
	int total = 0;
	do {
		total++;
		
		if (total <= 5) {
			
			cout << "Entering data for student: " << total << endl;
			cout << "Enter student name: ";
			cin >> name;
			outfile << name << endl;
			
			cout << "Enter student age: ";
			cin >> age;
			outfile << age << endl;
			
			cout << endl;
			
			cout << "Enter more student y/n? ";
			cin >> answer;
						
		} else {
			
			cout << "You can only enter not more than 5 students" << endl;
			break;
		}
		
	} while(answer == 'y' || answer == 'Y');

	
	outfile.close();
}

void readStudent(string names[], int ages[]) {
	
	fstream infile("students2.txt", ios::in);
	string name;
	int age;
	
	if (!infile)	
	{		
		cout << "While opening a file an error is encountered" << endl;
		return;	
	}	
	else {
		cout << "File is successfully opened" << endl;	
	}
	
	int index = 0;
	
	cout << "Reading from students2.txt - start" << endl << endl;
	while(!infile.eof())    
	{		
		cout << "Reading name from students2.txt - ";
		infile >> name;
		cout << name << endl;
		
		//read age from students.txt
		cout << "Reading age from students2.txt - ";
		infile >> age;
		cout << age << endl << endl;
		
		//add to array names and ages
		names[index] = name;
		ages[index] = age;	
		
		index++;
	}
	cout << "Reading from students2.txt - end" << endl << endl;	
		
	infile.close();	
}

void displayStudents(string names[], int ages[], int size) {
	
	cout << "Printing student name and age from array" << endl << endl;
	for (int i=0; i<size; i++) {
		cout << "Student [" << i+1 << "] name:" << names[i] << endl;
		cout << "Student [" << i+1 << "] age:" << ages[i] << endl;
		cout << endl;
	}
}
