我正在创建一个程序,该程序根据用户希望的方式对文件的内容进行排序。该文件包含学生的姓氏、名字、gpa 和家庭收入。我已经让我的程序根据用户的选择进行排序,包括姓氏、收入和 gpa。我的问题是,当程序对文件进行排序时,它最终只对收入、gpa 或姓氏进行排序。我希望它交换整条线。
例如,我在下面有 4 个名字,从左到右显示姓氏、名字、gpa 和家庭收入。
埃尔南德斯约书亚 3.40 65000
苏哈利 3.33 60000
唐 爱德华 4.00 100000
关洁西卡 3.20 50000
在我的程序按姓氏对文件进行排序后,它最终只对姓氏进行排序,而不更改其余数据以适应姓氏所在的位置。
关约书亚 3.40 65000
埃尔南德斯·哈里 3.33 60000
苏爱德华 4.00 100000
唐杰西卡 3.20 50000
这是我的班级人
void getData(Person student[], int& item)
{
ifstream fin;
fin.open("C:students.txt");
item = 0;
while(!fin.eof())
{
fin >> student[item].lastName >> student[item].firstName >> student[item].gpa >> student[item].income;
item++;
}
}
void swap(string& name1, string& name2)
{
//this is a swap function that swaps the data of the two string arguments.
string temp;
temp = name1;
name1 = name2;
name2 = temp;
}
void swap2(float& num1, float& num2)
{
//this is a swap function that swaps the data of the two float arguments
float temp;
temp = num1;
num1 = num2;
num2 = temp;
}
void sortByLastName(Person student[], int item)
{
//This for loop will put the items in alphabetical order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in alphabetical order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is bigger than the next item.
if(student[i].lastName > student[i+1].lastName)
swap(student[i].lastName, student[i+1].lastName);
}
}
void sortByGpa(Person student[], int item)
{
//This for loop will put the items in descending order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in descending order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is smaller than the next item.
if(student[i].gpa < student[i+1].gpa)
swap2(student[i].gpa, student[i+1].gpa);
}
}
void sortByIncome(Person student[], int item)
{
//This for loop will put the items in ascending order.
for(int j=0; j<item-1; j++)
{
//will perform the swapping until all items are in descending order.
for(int i=0; i<item-1; i++)
//will swap the two items next to each other if the first item is smaller than the next item.
if(student[i].income < student[i+1].income)
swap2(student[i].income, student[i+1].income);
}
}
void getChoice(int choice, Person student[], int item)
{
cout << "Press 1 to sort by last name. Press 2 to sort by gpa. Press 3 to sort by income.";
cin >> choice;
if(choice == 1)
sortByLastName(student, item);
else if(choice == 2)
sortByGpa(student, item);
else if(choice == 3)
sortByIncome(student, item);
}
void output(Person student[], int item)
{
//Displays all of the names to the screen.
for(int i=0; i<item; i++)
cout << student[i].lastName << " " << student[i].firstName << " " << student[i].gpa << " " << student[i].income << endl;
}