Problem: Programming Challenge #11 pg 489, Chapter 8, Using Files - String Selec
ID: 3555380 • Letter: P
Question
Problem: Programming Challenge #11 pg 489, Chapter 8, Using Files - String Selection Sort Modification in the Gaddis C++ Book.
You must first complete Programming Challenge #6 in Chapter 8.
Additional Requirements NOT in the book: Create a function to count how many last names begin with each letter and output the names and the total number of names each time (see Sample Output below). This function should be passed the array by value and the size of the array by value. The function should output the names that begin with a particular letter then output the total number of names. Do NOT output results for letters that do not have any names, i.e. for example ther are no names that begin with B, so no output should be generated for this letter.
Hint: Once you complete Programming Challenge #6, #11 is a slight modification. Chapter 5 covers reading data from a file (starting on pg. 275).
You can use Program 8-5 on page 471 to begin your project; you can easily modify this program to do a selection sort on strings instead of integers.
Constraints:
Collins, Bill
Smith, Bart
Allen, Jim
Griffin, Jim
Stamey, Marty
Rose, Geri
Taylor, Terri
Johnson, Jill Allison, Jeff
Looney, Joe
Wolfe, Bill
James, Jean
Weaver, Jim
Pore, Bob
Rutherford, Greg
Javens, Renee
Harrison, Rose
Setzer, Cathy
Pike, Gordon
Holland, Beth
WRITE THE PROGRAM: Write the program for the Problem above.
Hint: When reading in the names from the file you will want to use the getline() function. If you use the >> operator to read in the data from the file you will not be reading in the whole name (try it and see what happens).
Make sure you complete Programming Challenge #6 FIRST and get that program working completely before attempting to complete Programming Challenge #11.
Pseudo Code for main function:
Sample Output:
Explanation / Answer
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int get_input(string arr[])
{
ifstream myfile;
myfile.open("name.txt");
string line;
if(!myfile)
{
cout<<"unable to open name.txt"<<endl;
}
int i=0;
while(getline(myfile,line))
{
arr[i]=line;
i++;
}
return i;
}
void display(string arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
}
void sort_names(string arr[],int n)
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
string temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
int main()
{
string arr[200];
int n=get_input(arr);
cout << "Here are the unsorted names: ";
cout << "-------------------------- ";
display(arr,n);
sort_names(arr,n);
cout<<"Here are the names sorted: ";
cout << "-------------------------- ";
display(arr,n);
cout<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.