1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct persons{
string first_name;
string last_name;
};
void openfile(persons student[], int& item,ifstream&file);
void swappersons(persons& name1, persons& name2);
void sortbyfirstname(persons student[], int& item);
void output(persons student[], int& item);
void closefile(ifstream& file);
void sortbylastname(persons student[],int& item);
int main(){
int item,choice;
persons student[1000];
ifstream file;
openfile(student, item,file);
cout<<"please select an option"<<endl;
cout<<"select 1 to sort names by first name"<<endl;
cout<<"select 2 to sort names by last name"<<endl;
cout<<"select 3 to add a name"<<endl;
cin>>choice;
switch(choice)
{
case 1:
sortbyfirstname(student,item);
output(student, item);
break;
case 2:
sortbylastname(student,item);output(student, item);
break;
case 3:
cout<<"option still building"<<endl;
break;
default:
cout << "Invalid input, Terminating Program" << endl;
break;
}
closefile(file);
}
void openfile(persons student[], int& item,ifstream& file){
file.open("students");
if(file.fail()){
cout<<"file open error"<<endl;}
item=0;
while(!file.eof()){
file>>student[item].first_name>>student[item].last_name;
item++;
}
}
void swappersons(persons& name1, persons& name2){
persons temp;
temp=name1;
name1=name2;
name2=temp;
}
void sortbyfirstname(persons student[], int& item){
for(int a=0; a<item-1; a++)
{
for(int i=0; i<item-1; i++)
if(student[i].first_name > student[i+1].first_name)
swappersons(student[i],student[i+1]);
}
}
void sortbylastname(persons student[],int& item){
for(int a=0; a<item-1; a++)
{
for (int i=0; i<item; i++)
if(student[i].last_name>student[i+1].last_name)
swappersons(student[i],student[i+1]);
}
}
void output(persons student[], int& item){
for(int i=0; i<item; i++)
cout<< student[i].first_name<<" "<<student[i].last_name<<" "<<endl;
}
void closefile(ifstream& file){
file.close();
cout<<"input file closed"<<endl;
}
|