In: Computer Science
Using OOP, write a C++ program that will read in a file of names. The file is called Names.txt and should be located in the current directory of your program. Read in and store the names into an array of 30 names. Sort the array using the selection sort or the bubblesort code found in your textbook. List the roster of students in ascending alphabetical order. Projects using global variables or not using a class and object will result in a grade submission of 0.
The Names used for the Names.txt are: Jackie, Sam, Bill, Tom,
Mary, Paul, Zev, Barb, John, Sharon, Dana, Dominic, Steven,
Padro,,Katey, Kathy, Darius, Angela, Mimi,Jesse
Kenny, Lynn, Hector, Brittany, Jenn, Joe, Chloe, Geena, Sylvia,
Dean.
I tried this solution on this question and it had a lot of errors.
#include<iostream>
#include<fstream>
using namespace std;
//class read_name
class read_Name
{
private:
ifstream infile;
string name[30];
public:
//method prototypes
void setdata();
void sort();
void print();
};
//this method will read names from file and store it in array
void read_Name ::setdata()
{
int i=0;
//open the file
infile.open("names.txt");
//unable to open the file
if(!infile)
{
cout<<endl<<"Unable to
open the file";
exit(0);
}
//read the names from file
while(!infile.eof())
{
//read the names from file assign it to
name array
infile>>name[i];
i++;//increase the index
}
//close the file
infile.close();
}
//this method will print the names
void read_Name :: print()
{
int i;
//loop to print the names
for(i=0;i<30;i++)
{
cout<<"\t"<<name[i];//print
the name
}
}
//this method will print the names
void read_Name :: sort()
{
int i,j;
string t;
//loop to sort the names
//selection sort
for(i=0;i<30;i++)
{
for(j=i+1;j<30;j++)
{
if(name[i] > name[j])
{
//swap the names
t=name[i];
name[i]=name[j];
name[j]=t;
}
}
}
}
//driver program
int main()
{
read_Name obj; //declare an object
obj.setdata(); //call to setdata()
cout<<endl<<"Before
sort the data \n";
obj.print(); //call to print()
obj.sort(); //call to sort()
cout<<endl<<"After sort the data
\n";
obj.print(); //call to print()
}
output