Hi I am trying to answer this question for my homework:
Populate a text file EmployeeDetails.txt (for 20 employees) with details of each
employee on a single line. Details of an employee will consist of Name, Address, Age and
Salary. Write a C++ or Java program to implement an Employee Class to store the abovementioned
employee details. Create an array EmpArray of 20 Employee objects and fill
the array after reading the contents of EmployeeDetails.txt.
Then write a function Sort to sort the contents of EmpArray in ascending order (based
on their age) using any of the elementary sorting algorithms and display the contents of
the array prior to sorting and after sorting.
I wrote this so far:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Employee
{
public:
string name;
string address;
string age;
string salary;
};
void fill_file()
{
ofstream myFile("EmployeeDetails.txt");
myFile << "Emp1 P_louis 18 20,000\n";
myFile << "Emp2 P_louis 18 20,000\n";
myFile << "Emp3 P_louis 18 20,000\n";
myFile << "Emp4 P_louis 18 20,000\n";
myFile << "Emp5 P_louis 18 20,000\n";
myFile << "Emp6 P_louis 18 20,000\n";
myFile << "Emp7 P_louis 18 20,000\n";
myFile << "Emp8 P_louis 18 20,000\n";
myFile << "Emp9 P_louis 18 20,000\n";
myFile << "Emp10 P_louis 18 20,000\n";
myFile << "Emp11 P_louis 18 20,000\n";
myFile << "Emp12 P_louis 18 20,000\n";
myFile << "Emp13 P_louis 18 20,000\n";
myFile << "Emp14 P_louis 18 20,000\n";
myFile << "Emp15 P_louis 18 20,000\n";
myFile << "Emp16 P_louis 18 20,000\n";
myFile << "Emp17 P_louis 18 20,000\n";
myFile << "Emp18 P_louis 18 20,000\n";
myFile << "Emp19 P_louis 18 20,000\n";
myFile << "Emp20 P_louis 18 20,000\n";
myFile.close();
}
void main()
{
int x,y;
int len;
int i;
int count=0;
int pos;
int myArr[3];
Employee myArray[20];
string store;
string line;
fill_file();
fstream myFile("EmployeeDetails.txt");
while(!myFile.eof())
{
getline(myFile,line);
cout << line << endl;
pos=0;
i=0;
len=line.length();
while(i!=len)
{
if(line[i]==' ')
{
myArr[pos]=i;
pos++;
}
i++;
}
myArray[count].name=line.substr(0,myArr[0]);
myArray[count].address=line.substr((myArr[1]+1),(myArr[2]-(myArr[1]+1)));
cout << myArr[0];
cout << " ";
cout << myArr[1];
cout << " ";
cout << myArr[2];
cout << " ";
count++;
}
for(int j =0; j<20; j++)
{
cout << myArray[j].name;
cout << myArray[j].address;
}
myFile.close();
system("pause");
}
I get an error:
Unhandled exception at 0x763ffbae in Lab2_Addendum.exe: Microsoft C++ exception: std::out_of_range at memory location 0x001aeadc..
This line is supposed to cause that error:
myArray[count].address=line.substr((myArr[1]+1),(myArr[2]-(myArr[1]+1)));
I can't understand why it says its out of range when the pos and length I supplied is valid.
Whereas this line works fine(I checked by printing the name of each Employee after I commented out the troublesome line):
myArray[count].name=line.substr(0,myArr[0]);
Can someone please help me with that?