You are given a file named “students.txt” consisting of students\' names on sepa
ID: 3692892 • Letter: Y
Question
You are given a file named “students.txt” consisting of students' names on separate lines in the following form (note that some students might not have a middle name): lastName, firstName middleName Write a program that converts and prints 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 a string containing a student's name as input and returns a string containing the altered name. Use the string function find to find the index of ',' Use the string function length to find the length of the string Use the function substr to extract the firstName, middleName, and lastName Answer must be in C++
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <fstream>
using namespace std;
string nameModifier(string name)
{
int firstSpace = name.find(" ");
string newString = "";
string lastName = name.substr(0, firstSpace);
string partString = name.substr(firstSpace+1);
int secondSpace = partString.find(" ");
string firstName, middleName;
if(secondSpace == -1)
{
firstName = partString;
return firstName+" "+lastName;
}
else
{
firstName = partString.substr(0, secondSpace);
middleName = partString.substr(secondSpace+1);
return firstName+" "+middleName+" "+lastName;
}
}
int main()
{
//You are given a file consisting of students’ names in the following form: lastName, firstName middleName.
ifstream input;
input.open("Names.txt");
ofstream output;
output.open("NewNames.txt");
//Your program must read each student’s entire name into a variable and must call
//a function that takes as input a string, consisting of a student’s name,
//and returns a string consisting of the altered name.
string name, newName;
while(!input.eof())
{
getline(input, name);
newName = nameModifier(name);
//Output the altered name into a file.
output<<newName<<endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.