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.
//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;
}
Comments