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<string>
using namespace std;
string alteredName(string in)
{
string input =in;
int i=0;
//clear spaces from begin
while(input[i++]==' ');
i--;
input=input.substr(i);
//find lastName
int pos=input.find(",");
string lastName=input.substr(0,pos);
i=0;
//clear spaces from end of lastName
while(lastName[i++]!=' ');
i--;
lastName=lastName.substr(0,i);
//update input
input=input.substr(pos+1);
i=0;
//clear spaces
while(input[i++]==' ');
i--;
input=input.substr(i);
//find firstName
pos=input.find(",");
string firstName=input.substr(0,pos);
//update input
input=input.substr(pos+1);
i=0;
//clear spaces
while(input[i++]==' ');
i--;
input=input.substr(i);
//find middleName
pos=input.find(",");
string middleName=input.substr(0,pos);
return firstName+" "+middleName+" "+lastName;
}
int main()
{
string arr[]={ {" Roosevelt, Franklin, Delano"},
{"Trumann, Harry, S." },
{" Churchill, Winston, Leonard"} };
cout<<"Primary array: \n";
for(int i=0;i<3;i++)
{
cout<<arr[i]<<endl;
}
cout<<"\nResult is: \n";
for(int i=0;i<3;i++)
{
cout<<alteredName(arr[i])<<endl;
}
}
Comments
Leave a comment