In: Computer Science
In this lab, you will read and write to a file, as well as sorting the information. Copy and paste the following into a file named "inputs.txt":
7 199922007 C.J. Cregg Political_Science 200822013 Olivia Dunham Criminal_Justice 199822007 Josh Lyman Law 199922006 Toby Ziegler Communications 200922015 Leslie Knope Public_and_Environmental_Affairs 199922004 Sam Seaborn Law 200722013 Walter Bishop General_Sciences
The input file provides details for a student database in the following format:
Number_of_students ID_Number Student_First_Name Student_Last_Name Major …… ID_Number Student_First_Name Student_Last_Name Major
Your program will read specific information from the file and continue reading the contents of the body from the file until the EOF (end of file) character. You will write the following information to an output file:
Each section of information should be labeled in the output file in all capital letters. A struct should be used to store and manipulate the file information between reading and writing the file. You must include the follow three functions with the exact prototypes:
student* create_student_db(int); void get_student_db_info(student *, int, fstream &); void delete_student_db_info(student *);
Your main function needs to check to make sure the file you open exists before moving forward. If the file doesn’t exist, then you need to provide an error message and prompt the user to enter a file name that does exist.
fstream documentation: http://www.cplusplus.com/reference/fstream/fstream/ (Links to an external site.)
Implementation
Now, implement the driver.cpp, student_db.cpp, and student_db.h files. Create a Makefile to manage the compilation of all these files. You can adapt the Makefile that was posted on the Lectures page in Canvas.
A Note on Sorting
There are many different algorithms that can be used to sort data. For the purposes of this lab, one of the simplest algorithms to implement is a version of the bubble sort algorithm. Bubble sort works by repeatedly comparing two elements in a collection of data, and swapping them. It continues through all of the data until no more swaps are needed, indicating that the data is sorted.
Bubble Sort reference: https://www.geeksforgeeks.org/bubble-sort/ (Links to an external site.)
TAR Files
When you begin to have projects with multiple files, it becomes useful to have a way to group them together for uploading, emailing, or archiving. TAR files (also known as tarballs) are classic way to do this on Linux machines, and are what you will use for programming assignment submissions.
To create a tar file, use the tar command. There are multiple options that can be added, with examples and explanations at the reference material below. The ones included in the example below are -c, -v, and -f.
tar –cvf ...
The -c option is used to create the tar file. The -f option is used to specify which tar file to use, followed by the filename (ending in .tar) that you specify. The -v option stands for "verbose", and prints the files being added to the tar file to the terminal as the tar command executes.
After the command, options, and chosen .tar filename, you must include all of the files that you want to be added, separated by a space.
To extract the files from a tarball, you can use the following command, where the -x option stands for "extract":
tar –xvf
Prove that you can make a tarball with multiple files, and then extract the files from it. Make sure that when creating the tarball you specify the .tar filename, and to extract the files into a different directory than the original.
Save the below file as "student_db.h"
#include <cstring>
using namespace std;
struct student
{
int ID;
string firstName;
string lastName 3;
string major;
};
int get_num_students(char *fileName);
student *create_student_db(int numStudents); void get_student_db_info(student *students, int numStudents, fstream *rf);
void sort_last_name(student *students, int numStudents);
void sort_ID(student *students, int numStudents);
int get_num_majors(student *students, int numStudents);
void output_info(student *students, int numStudents);
void output_sorted_last(student *students, int numStudents);
void output_sorted_ID(student *students, int
numStudents);
fstream rf;
// Opens the read file
rf.open(fileName, fstream::in | fstream:out | fstream:app);
//Stores how many students need to be created
rf >> numStudents;
// Closes file
rf.close();
//returns numStudents
return numStudents;
}
student *create_student_db(int numStudents)
{
// Create a student pointer
student *students;
//point pointer to an array made on the heap of size numStudents
students = new student[numStudents]:
//return pointer
return students;
}
void get_student_db_info(student *students, int numStudents, fstream *rf)
}
else if (k == (min_length(students[j -
1].lastName, students[j].lastName) - 1))
{
if (students[j - 1].lastName.length() > students[j].lastName.length())
{
student temp = students[j - =
students[j - 1] = students[j];
students[j] = temp;
1];
}
}
}
}
int min_length(string word1, string word2)
{
// Return the number that is the smallest
if (word1.length() < word2.length()
{
}
return word.length();
return word 2.length();
}
// Loop through the letters of the current
names
for (int k = 0; k< min_length(students[j - 1].lastName, students[j].lastName); k++)
{
//Compare letters and if the words are out of order, switch and break to the next words
if (students[j - 1].lastName[k] > students[j].lastName[k])
{
student temp = students[j - 1]; students[j 1] = students[j]; students[j] = temp;
break;
}
//f the words are already sorted alphabetically, stop sorting the current words and switch to the next ones
else if (students[j - 1].lastName[k] < students[j].lastName[k])
{
break;
// If the words have been the same so for and the end of one of the words has been reached, make the shorter word first
else if (k == (min_length(students[j]
// Open the output file
wf.open("StudentInfo.txt", fstream::out| fstream::app);
wf << "SORTED BY LAST NAME: ";
//For loop runs for new Students for (int i = 0; i < numStudents; i++)
{
// Current student info printed to file wf«< students[in].last Name << "";
// Close file wf.close();
}
wf << endl
<< endl;
}
void output_sorted_ID(student *students, int numStudents)
{
// Create an output file object
ofstream wf;
//Open the output file
wf.open("StudentInfo.txt", fstream::out| fstream:app);
wf.open("StudentInfo.txt", fstream::out | fstream::app);
wf << "SORTED BY ID NUMBER: ";
//For loop runs for new Students
for (int i = 0; i < numStudents; i++)
{
// Current student info printed to file wf << students[i].firstName << <<
students[i].ID <"";
} wf << endl
<< endl;
;
// Close file wf.close();
}
void output_num_majors(int num Majors)
{ {
// Create an output file object
ofstream wf;
// Open the output file
wf.open("StudentInfo.txt", fstream::out | fstream::app);
wf << "NUMBER OF UNIQUE MAJORS:"<< num Majors;
** Function: get_input
** Description: Gets input from the user to store in a C-style string
** Parameters: None
** Pre-Conditions: None
** Post-Conditions: None
char *get_input()
{ {
char *str = new char[1];
*str = '\0';
cout << "Please enter a file name to read from: ";
while (cin.peek() != '\n')
{
add_one_char(&str, cin.get();
}
cin.ignore();
cin.clear();
return str;
}
void add_one_char(char **str, char c)
}
//else if the last index is reached, add one
number Majors
else if (j == numStudents 1)
{
nus Majors;
to
//Add one to number Majors to account for the last guy not being counted, his will be unique because if someone had his before, it would not have been counted because of him
nus Majors;
//Output the number of unique num Majors output num majors(num Majors);
}
void delete_student_db_info(student **students, int numStudents)
{ {
// Delete memory on heap
delete[] * students;
// Point pointer to NULL
*students = NULL;
}
{
char *temp = new char[strlen(*str) + 2];
for (int i = 0; i < strlen(*str); i++)
{ {
temp[i] = (*str)[i];
}
temp[strlen(*str)] = c;
temp[strlen(*str) + 1] = '\0'; =
delete[](*str);
(*str) = new char[strlen(temp) + 1];
strcpy((*str), temp);
delete[] temp;
}
Include iostream
include cstifLib.to
include cstring
include eftrea
include "student .h
using namespace std;
Int get_num_ students car F )
student
roce the ral File rf.open(Filename, Fetrendz | fstream: tout I fstream app): Starch students need to be treated
arts students;
rf.close();
(Ireturns tiulmts return on students;
student create_student_idbint students)
Ligeate a student pointer
student student
/point pointer to an array wide the bea ut NUN students students - in student [mom student J:
return pointer return students:
wdd get student db info(student
string daytime:
skip a line Rolling, dubLin);
229
211
732
2
215
delete my in he deleted) students;
7 pointer to "students- MKET
Tinction get input parameterS
** Description: Gets input from the user to store in style string
* -ods Mine
*
Post-Conditions one
PHERCOD
Thar "get input ()
char str- char
cout Please enter a file name ta read from: wille (cin.peer)
add one char (Rasta, in.cet()
cin.ignore(): cin cin
return string
curd add one char(char*str, char c)
char temp = no strlen(str) 1 2]
fon (int 1- ic strien(str); 1)
tempi] - ("str)[#];
tumstrinstr)
Save the below file as "driver.cpp"
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include "student_db.h"
using namespace std; int main(int argc, char **argv)
{
student *students;
char *fileName;
int numStudents;
// Create read file object
fstream rf;
// Make sure read file exists, otherwise ask for new read file name
do
{
fileName = get_input();
rf.open(fileName, fstream::in);
if (rf.good() != true)
{
cout << "ERROR THAT FILE DOES NOT EXIST!" << endl;
}
} while (rf.good() != true);
//Call a function that opens the read file and check how many students need to be created
numStudents = get_num_students(fileName);
delete[] fileName;
// Call function state* create_student_db(int) which will create an array of students on the heap and return the memory address
students = create_student_db(numStudents);
// Call function void get_student_db_info(student*, int, fstream &) that
in trige
edunet tn try ave il
IN e e a
nt , a
Tod NSW wS I
t Ie a e le a
tt et t ri
t ertita me in ctet date
By state .
S ar s dt:
t the e
S
SM P T f
TTV
VE n VE _L IW, IN EE H R RAEE WNTER
WII U ATen
N ti MA
NI IN a he YE ila ler
N A eA He Sakin
S1 nd e e wary m e
Save the below file as "StudentInfo.txt"
7
199922007 C.J. Cregg Political Science 200822013 Olivia Dunham Criminal Justice 199822007 Josh Lyman Law
199922006 Toby Ziegler Communications
200922015 Leslie Knope Public and Environmental Affairs 199922004 Sam Seaborn Law
200722013 Walter Bishop General Science
199922007 C.). Crazy Political Science
206822913 Olivia Dunham Criminal Justice
199822007 Josh Lyman Law
199922006 Toby Ziegler Communications 200922015 Leslie Knope Public and Environmental Affairs
199922004 Sam Seaborn Law 200722013 Walter Bishop General Science
//Call function void get_student_db_info(student*, int, fstream &) that populates student array with information
get_student_db_info(students, no Students,
&rf);
//Close the read file
rf.close();
//Call function that will sort the students by last name
sort_last_name(students, numStudents);
//Call function that will output the students to an output file sorted by last name
output_sorted_last(students, numStudents); // Call function that will sort the students by ID
Number
sort_ID(students, numStudents);
//Call function that will output the students sorted ID to an output file
output_sorted_ID(students, numStudents);
// Call function that will calc and output the number of unique majors
get_num_majors(students, numStudents);
//Call function void
delete_student_db_info(student**, int) that willdelete the memory on the heap
delete_student_db_info(&students, no Students);
}
//Close file
wf.close();
}
int get_num_majors(student *students, int numStudents)
{
// Create int num Majors
int numMajors = 0; =
//Create string current Major
string current Major;
//For loop runs through numStudents
for (int i = 0; i < (numStudents); i++)
{
// Store current students major in a variable current Major = students[i].major;
//For loop starts one ahead of previous for loop and runs through numStudents
for (int j = (i + 1);j< numStudents; j++)
{ // If stored major equals current students major, break out of loop
if (current Major %3= students[j].major)
{
break;
for (int j = 1; j <= i; j++)
// If the student IDs are out of order, switch
if (students[j - 1].ID > students[j].ID)
{
student temp = students[j - 1];
students[j - 1] = students[j];
students[j] = temp;
them
}
}
}
//Sort the students by last name by comparing and switching based on predefined rules
void sort_last_name(student *students, int numStudents)
{
// Loop through all students
for (int i = numStudents - 1; i >= 0; i--)
{
// Loop through the students that are yet to be fully sorted
for (int j = 1; j<= i; j++)
{
//Output functions
void output_info(student *students, int num Students)
{
// Create an output file object
ofstream wf;
//Open the output file
wf.open("StudentInfo.txt", fstream::out fstream::app);
//For loop runs for new Students
for (int i = 0; i < numStudents; i++)
{
1/ Current student info printed to file
wf<< students[i].ID <<""<< students[i].firstName << << students[i].lastName << students[i].major << endl;
<<
}
// Close file wf.close();
}
void output_sorted_last(student *students, int numStudents)
{
//Create an output file object
ofstream wf;
void output_num_majors(int num Majors);
int min_length(string word1, string word2); void delete_student_db_info(student **students, int numStudents);
char *get_input();
void add_one_char(char **str, char c);
#include string
using namespace std
struct student
Int 10;
string first ; string last string major;
Tnt get num students (char filename); student create student db(int numstudents);
void get student db info(student students, Int no students, Fire
void port_last_na(student student, int num student);
vold sort_ID(student student, int mun students); Int get nun nia jors(student students, Int hustudents): void output_info(student "students, Int rstudent s):
void output sorted list(student "students, Int num students);
void output sorted 1D(students students, In students)
void output nu aja stint nata jor);
Int min length(string word, string word);
vol delete student db info(student students, students);
char eet_input(); void add one char(char str, char c);
Save the below file as "student_db.cpp"
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <fstream>
#include "student_db.h"
using namespace std;
int get_num_students(char *fileName)
int numStudents;
string dummyLine;
//Skip a line
getline(*rf, dummyLine);
// Have a for loop run for non Students
for (int i = 0; i < numStudents; i++)
{
//For the current student, assign the info from the readfile to the correct attributes. Done based on space flags and known order
*rf >> students[i].ID;
*rf>> students[in].first Name;
*rf >> students[i].lastName;
*rf >> students[i].major;
}
//Sort the students by ID number by comparing and switching based on predefined rules
void sort_ID(student *students, int numStudents)
{
//Run through all the students
for (int i = numStudents - 1; i >= 0; i--)
{
{