You are given a file consisting of students’ names in the following form: lastNa
ID: 3681705 • Letter: Y
Question
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.
Note: This program needs the ability to have an input and output stream because we have to pull information from outfile, run it through our program, and then output the information to the another data file. Please keep it to somewhat simple code as I am relatively new to this. And I am not familiar with Java, either. Thank you SO much!
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;
}
}
If you need any refinements, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.