Answer to Question #183021 in C++ for Vincenzo Santoro

Question #183021

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-04-30T16:52:31-0400
//student.txt has names saved as lastname,firstname,middlename
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void names(string filename){
    string input, firstName = "", middleName = "", lastName = "";
    fstream file;
    int pos0, pos1, count = 0;
    file.open(filename);
    if(!file) cout<<"Error opening file";
    else 
        while(getline(file, input)){
            middleName = "";
            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);
            cout<<firstName + " " + middleName + " " + lastName<<endl;
            count = 0;
        }
}
int main(){
    string file = "students.txt";
    names(file);
    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

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS