Question

In: Computer Science

This assignment is to give you practice using enums, string variables, and string functions. In order...

This assignment is to give you practice using enums, string variables, and string functions. In order to get full credit for the program you must use these three topics.

You are to write a program that will read a series of names of people from a data file that has been created with extra blank spaces and reformat the names into a standardized format.

The datafile is mp6names.txt. It is arranged with the information for one person on each line. The first character on the line will be either ‘M’ or ‘F’ indicating the gender of the person, and the second character will be either ‘M’, ‘S’, or ‘D’ indicating married, single or divorced. You may assume that there will be no bad data here. The remainder of the line is the person’s name in the form:

Last_name, First_name Middle_Initial.

Note that there will always be a comma immediately after the last name and, if the person has middle initial, it will always be followed by a period. However, there could be any number of blank spaces in between each part of the name and some people do not have middle initial.

Your task is to clean up the name and print it out in the standard format, e.g. Mr. Bill T. Jones with the appropriate title and exactly one space between each part of the name.

You are REQUIRED to use functions, enums, string variables and string functions in the solution to this problem. Define an enum for the Marital Status of the person (with the values SINGLE, MARRIED and DIVORCED) and write a function that reads in the character from the file and returns the appropriate enum value.

Read the name from the file into a string variable and write another function that uses the functions of the string class (e.g. find(), substr() etc.) to clean up the name and create a new string variable containing the name in the new format.

Finally, add the appropriate title to the name and print it out. All males will have the title “Mr.” – married females will have “Mrs.” and single or divorced females will have “Ms.”

Continue doing this until the end of file is reached. Your output must include the original name as read from the file followed by the new name in the standardized format.   For formatting purposes you may assume that no name will have more than 30 characters.

This is just a SUGGESTED method and for each step you may want to include output for debugging purposes to insure that your program is working correctly. Feel free to design your own modules as you like. A sample output from the first few lines of the data file follows:

Original name                  Standardized name

Bach,   Johann    S.         Mr. Johann S. Bach
Curie,     Marie A.            Mrs. Marie A. Curie
Parker, Alice   M.             Ms. Alice M. Parker

Solutions

Expert Solution

Solution:

  • Create enum for Gender and Marital status.
  • Create methods getGender() and getMaritalStatus() to fetch above enum values based on character.
  • I have defined trim() to remove extra white spaces.
  • Make changes in code to read input from file, I have commented those 2 lines and I am taking input from user. Change it accordingly.
  • String functions used: substr(), istringstream, string.length().

Code in C++:

#include <bits/stdc++.h>
#include <fstream>
    
using namespace std;

// Create enums
enum Gender {MALE, FEMALE};
enum Marital_Status {SINGLE, MARRIED, DIVORCED};

// Method to fetch gender based on character
Gender getGender(char s){
    if(s=='M')
        return MALE;
        
    return FEMALE;
}

// Method to fetch Marital Status based on character
Marital_Status getMaritalStatus(char s){
    if(s=='S')
        return SINGLE;
    if(s=='M')
        return MARRIED;
        
    return DIVORCED;
}

//Trim white spaces in string
string trim(const string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (string::npos == first)
    {
        return str;
    }
    
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

int main() {
    string line;
        
        cout<<"   Original name"<<"\t\t\t"<<"   Standard name"<<endl;
        

    // Uncomment below 2 lines to read data from file
    // ifstream infile("mp6names.txt");
    // while (getline(infile, line)){

        while(getline(cin, line)){                  // Remove this line if you want to read data from file
            
            // Use it to trim line based on white spaces
            istringstream ss(line);
            string token;
            
            int i=0;
            Gender g;
            string Standard="", Original="", last=""; 
            
            // Store original string
            Original = line.substr(2, line.length()-2);
            
            // Fetch tokens from line that is read
            while(getline(ss, token, ' ')) {
                // Check for extra white spaces
                if(trim(token)=="")
                    continue;
                    
                // First token contains gender, marital status, last name
                if(i==0){
                    g = getGender(token[0]);
                    
                    if(g == MALE)
                        Standard += "Mr.";
                    else if(getMaritalStatus(token[1]) == MARRIED)
                        Standard += "Mrs.";
                    else
                        Standard += "Ms.";
                    
                    last = token.substr(2, token.length()-3);
                }
                //Second token contains first name
                else if(i==1){
                Standard += " " + trim(token);              
                }
                // Third token contains middle name
                else{
                    Standard += " " + trim(token); 
                }
            i++;
        }
        
        // Store it in Standard format
        Standard += " " + last;
        cout<<Original<<"\t\t\t"<<Standard<<endl;
        }
        
        
        return 0;
}

Input: Example from file

MMBach,   Johann   S.
FMCurie,     Marie A.
FSParker, Alice   M.
MSPinkman, Jesse   

Output:

   Original name                     Standard name
Bach,   Johann   S.                     Mr. Johann S. Bach
Curie,     Marie A.                     Mrs. Marie A. Curie
Parker, Alice   M.                      Ms. Alice M. Parker
Pinkman, Jesse                          Mr. Jesse Pinkman

PS: Let me know if you have any doubt especially in reading input from file.


Related Solutions

in c++ language This assignment is to give you practice using structs and sorting. In competitive...
in c++ language This assignment is to give you practice using structs and sorting. In competitive diving, each diver makes dives of varying degrees of difficulty. Nine judges score each dive from 0 through 10 in steps of 0.5. The difficulty is a floating-point value between 1.0 and 3.0 that represents how complex the dive is to perform. The total score is obtained by discarding the lowest and highest of the judges’ scores, adding the remaining scores, and then multiplying...
This assignment will give you practice in Handling Exceptions and using File I/O. Language for this...
This assignment will give you practice in Handling Exceptions and using File I/O. Language for this program is JAVA Part One A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Prompt the user for data to write the file. Part Two Write a program that...
This assignment is to give you practice using struts, arrays, and sorting. (Objective C++ and please...
This assignment is to give you practice using struts, arrays, and sorting. (Objective C++ and please have a screenshot of output) In competitive diving, each diver makes dives of varying degrees of difficulty. Nine judges score each dive from 0 through 10 in steps of 0.5. The difficulty is a floating-point value between 1.0 and 3.0 that represents how complex the dive is to perform. The total score is obtained by discarding the lowest and highest of the judges’ scores,...
Programming Assignment #3: SimpleFigure and CirclesProgram Description:This assignment will give you practice with value...
Programming Assignment #3: SimpleFigure and CirclesProgram Description:This assignment will give you practice with value parameters, using Java objects, and graphics. This assignment has 2 parts; therefore you should turn in two Java files.You will be using a special class called DrawingPanel written by the instructor, and classes called Graphics and Color that are part of the Java class libraries.Part 1 of 2 (4 points)Simple Figure, or your own drawingFor the first part of this assignment, turn in a file named...
Assignment Overview IN C++ This assignment will give you practice with numerical calculations, simple input/output, and...
Assignment Overview IN C++ This assignment will give you practice with numerical calculations, simple input/output, and if-else statements. Candy Calculator [50 points] The Harris-Benedict equation estimates the number of calories your body needs to maintain your weight if you do no exercise. This is called your basal metabolic rate or BMR. The calories needed for a woman to maintain her weight is: BMR = 655 + (4.3 * weight in pounds) + (4.7 * height in inches) - (4.7 *...
Assignment Overview This assignment will give you practice with interactive programs and if/else statements. Part 1:...
Assignment Overview This assignment will give you practice with interactive programs and if/else statements. Part 1: User name Generator Write a program that prompts for and reads the user’s first and last name (separately). Then print a string composed of the first letter of the user’s first name, followed by the first five characters of the user’s last name, followed by a random number in the range 10 to 99. Assume that the last name is at least five letters...
Decision Structures Calorie Calculator Assignment Overview This assignment will give you practice with numerical calculations, simple...
Decision Structures Calorie Calculator Assignment Overview This assignment will give you practice with numerical calculations, simple input/output, and if-else statements. Program Objective: In this exercise, you will write a program the calculates the Daily Caloric needs for weight lose diet. According to everydayhealth.com they recommend this daily caloric formula for a weight loss diet: BMR + Activity Level - 500 calories. Calories Calculator The Harris-Benedict equation estimates the number of calories your body needs to maintain your weight if you...
C++ program to read line comments. This assignment will give you a little bit of practice...
C++ program to read line comments. This assignment will give you a little bit of practice with string parsing. Your task is to write a program that reads in a .cpp file line-by-line, and prints out only the text that's after the // characters that indicate a single-line comment. You do not have to worry about /* multiline comments */ though there will be a small amount of extra credit for programs that correctly extract these comments as well.
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will...
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will use the concept of object aggregation (i.e., has-a relationship between objects). You will implement a Java application, called MovieApplication that could be used in the movie industry. You are asked to implement three classes: Movie, Distributor, and MovieDriver. Each of these classes is described below. The Movie class represents a movie and has the following attributes: name (of type String), directorsName (of type String),...
Using the string functions below, write new functions to do the following, and test them in...
Using the string functions below, write new functions to do the following, and test them in your main() function: Determine whether the first or last characters in the string are any of the characters a, b, c, d, or e. Reverse a string Determine whether a string is a palindrome (spelled the same way forward or backward FUNCTIONS REFERENCE: string myString = "hello"; // say we have a string… // … we can call any of the following // string...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT