Answer to Question #274863 in C++ for jjl

Question #274863

You are given a file consisting of students’ names in the following form: lastName, firstName middleName. (Note that a student may not have a middle name.)

Write a program that converts each name to the following form: firstName middleName lastName. Your program must read each student’s entire name in a variable and must consist of a function that takes as input a string, consists of a student’s name, and returns the string consisting of the altered name to print to the terminal. Use the string function find to find the index of ,; the function length to find the length of the string; and the function substr to extract the firstName, middleName, and lastName.


1
Expert's answer
2021-12-03T02:05:55-0500
#include <iostream>
#include <fstream>
#include <string>


using namespace std;


string names(string input){
    string firstName = "", middleName = "", lastName = "";
    int pos0, pos1, count = 0;


    for(int i = 0; i < input.length(); i++){
        if(input[i] == ','){
            if(count == 0){
                pos0 = i;
                count++;
            }
            else{
                pos1 = i;
                count++;
            }
        }
    }
    if(count == 1) pos1 = input.length();
    lastName = input.substr(0, pos0);
    firstName = input.substr(pos0 + 1, pos1 - pos0 - 1);
    if(count == 2) middleName = input.substr(pos1 + 1);


    return firstName + " " + middleName + " " + lastName;
}
int main(){
    string filename = "students.txt", line;
    fstream file;
    file.open(filename);
    if(!file){
        cout<<"Error opening file";
        return 0;
    }
    while(!file.eof()){
        getline(file, line);
        cout<<names(line)<<endl;
    }


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment