This lab will introduce you to structs and sorting. In this lab, you will read unsorted data from a file into an array of structs. You will then sort the array of structs based on each of the elements in the struct.
In this lab you will take data from a file into a struct, and then sort the data within the struct. You will:
1. Define a struct that holds 3 pieces of data, a string containing a first name, a string containing a last name, and a floating point number containing a score. The struct you should add to your program looks like:
struct student {
string first;
string last;
float score;
};
2. Prompt the user to enter in an input file name.
3. Try and open the input file name the user passed in (2). If the input file name is unable to be opened, an error should be displayed and you should loop from (2) until a valid file name is passed. The error should display:
Error: invalid input file name
4. Once you have a valid file name, read in the data from the file into a vector of structs. For this lab any input file will be guaranteed to have 10 students in it. Thus you can make your vector of structs statically be the size of 10.
5. Output, to a file, the vector of structs sorted with bubble sort in the following ways:
You will need to declare/define 3 functions to do this:
1. sortByFirst(vector< student>&) - This function will sort (returning via reference) the vector of student structs passed to it by the student's first names using bubble sort.
2. sortByLast(vector< student>&) - This function will sort (returning via reference) the vector of student structs passed to it by the student's last names using bubble sort.
3. sortByScore(vector< student>&) - This function will sort (returning via reference) the vector of student structs passed to it by the student's scores using bubble sort.
Pseudo-code of bubble sort is as follows:
procedure bubbleSort(A := list of sortable items)
swapped := false
for i:= 0 to length(A)-1
for j:= 0 to length(A)-i-1
if (A[j] > A[j+1]) then
swap(A[j], A[j+1])
swapped := true
end if
end for
if (!swapped) then
break
end for
end procedure
An example of an interaction with your program is shown below, your output should match these examples exactly. (The words printed in blue are from the computer, based on your commands, the words in red are user input. Note: these colors are simply here to distinguish components and not needed in your program.):
Alexs-iMac:lab13 alex$ ./a.out
Enter an input file name
**error.txt
Error: invalid input file name
Enter an input file name
**error
Error: invalid input file name
Enter an input file name
**lab13in.txt
Sorted by first name...
Sorted by last name...
Sorted by score...
See lab13out.txt for sorted arrays