Write a program to read student data from the standard input, sort it by last na
ID: 3634110 • Letter: W
Question
Write a program to read student data from the standard input, sort it by last name / first name, and print out the result to standard output (one row per student). The student data consists of a last name, first name, and a gpa (floating point). You may assume no more than 50 students.i know how to cout alphabetically, but when a name has more characters i don't know how to sort them.
eg: (william) should be arranged before (will)
same applies to the first name if there are more than 2 same last names.
Explanation / Answer
Dear,
#include<iostream>
//Header file for stirngs
#include<string>
//Header file for formatting display
#include<iomanip>
using namespace std;
const int RECORDS=50;
//structure of Student
struct Student
{
string firstName;
string lastName;
float gpa;
};
void sortFirstname(Student []);
void displayRecords(Student []);
Student s[RECORDS];
int main()
{
//Reading records from console
for(int i=0;i
{
cout<<"Enter first Name : ";
cin>>s[i].firstName;
cout<<"Enter last Name : ";
cin>>s[i].lastName;
cout<<"Enter gpa : ";
cin>>s[i].gpa;
}
//sorting by uisng first name
sortFirstname(s);
displayRecords(s);
//sorting by using last name
sortLastname(s);
displayRecords(s);
system("pause");
return 0;
}
//To sort records by lastnames of Student
void sortFirstname(Student s[])
{
string tempFirst;
string tempLast;
float tempGpa;
//cout<<"First Name"<<"LastName"<<"Gpa "<
for(int i=0;i
{
for(int j=0;j
{
if(s[j].firstName.compare(s[j+1].firstName)>0)
{
//bubble sort
tempFirst=s[j].firstName;
s[j].firstName=s[j+1].firstName;
s[j+1].firstName=tempFirst;
tempLast=s[j].firstName;
s[j].firstName=s[j+1].firstName;
s[j+1].firstName=tempLast;
tempGpa=s[j].gpa;
s[j].gpa =s[j+1].gpa;
s[j+1].gpa=tempGpa;
}
}
}
}
//To sort records by lastnames of Student
void sortLastname(Student s[])
{
string tempFirst;
string tempLast;
float tempGpa;
//cout<<"First Name"<<"LastName"<<"Gpa "<
for(int i=0;i
{
for(int j=0;j
{
if(s[j].lastName.compare(s[j+1].lastName)>0)
{
//bubble sort
tempLast=s[j].lastName;
s[j].lastName=s[j+1].lastName;
s[j+1].lastName=tempLast;
tempLast=s[j].firstName;
s[j].firstName=s[j+1].firstName;
s[j+1].firstName=tempLast;
tempGpa=s[j].gpa;
s[j].gpa =s[j+1].gpa;
s[j+1].gpa=tempGpa;
}
}
}
}
//To display total records
void displayRecords(Student s[])
{
cout<<"First Name"<<"LastName"<<"Gpa "<
for(int i=0;i
cout<<<<<<
}
Note:Run the program using visual studio 2010 vc++
Hope this would helpful to you..
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.