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.
#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;
}
Comments
Leave a comment