(C++ Programming) You are given a file consisting of students’ names in the foll
ID: 3683436 • Letter: #
Question
(C++ Programming) You are given a file consisting of students’ names in the following form: lastName, firstName middleName. (Note that some students 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 into a variable and must contain a function that takes as input a string, consisting of a student’s name, and returns a string consisting of the altered name. • Use the string function find to find the index of , • the function length to find the length of the string • the function substr to extract the firstName, middleName and lastName. Output the altered name into a file. This program has no user interface.
Banks,John William
Barret,Ron
Drew,Lucy Marie
Perry,Mark G
Smith,John Carr
Explanation / Answer
input.txt
Banks,John William
Barret,Ron -
Drew,Lucy Marie
Perry,Mark G
Smith,John Carr
Solution.cpp
#include <iostream>//input output function header file
#include <string>//string function header fiile
#include <fstream>//file operation headerfile
using namespace std;//includes std namespace
void getFullName();//function declaration
int main()
{
getFullName();//calling function
return 0;//main function return type integer so returns zero
}
void getFullName()//function definition
{
string fullName;
ifstream inData;
string lastName;
string middleName;
string firstName;
int pos1,pos2;
int totallen;
inData.open("input.txt");
cout<<"firstName"<<endl;
cout<<"middlename"<<endl;
cout<<"lastName";
cout<<endl;
while ( getline(inData, fullName)) {
pos1 = fullName.find(",");//position at ,
pos2 = fullName.find(" ");//position at space
lastName = fullName.substr(0, pos1);//get lastname
totallen = fullName.length();//totallength of theline
firstName = fullName.substr(pos1+1, pos2-pos1);//gets firstname
middleName=fullName.substr(pos2+1,totallen-pos2);//gets middlename
cout << firstName<<endl;
cout<<middleName<<endl;
cout<<lastName;
}
while (getline(inData, fullName));
inData.close();//closing file
}
output
firstName middlename lastName
John William Banks
Ron - Barret
Lucy Marie Drew
Mark G Perry
John Carr Smith
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.