You are given a file, “names.data”, consisting of several students’ names in the
ID: 3764282 • Letter: Y
Question
You are given a file, “names.data”, consisting of several students’ names in the following form: lastName, firstName middleName (Note that a student may not have a middle name, but also that individual parts of the name will contain no spaces). Write a program that reads in each name from the file, converts each name to the following, and displays it: firstName middleName lastName Your program must read in the entire name into one string variable. In addition, your program must contain one user-defined function that takes the string variable that contains the name, and returns a string that contains the altered name.
global variables are not allowed to be used.
Explanation / Answer
This below script will as per given problem statement and perform the string alternation using string alter function.
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <algorithm>
using namespace std;
string alter_string(string s)
{
return s.replace(8,10,"just a");
}
int main()
{
const char* filename = "C:\Users\jnarasim\Desktop\Names.txt";
ifstream inFile(filename);
ifstream inFile1(filename);
int count = 0;
string name;
if(!inFile)
{
cout <<"Failed to open file" << filename;
return 1;
}
cout<<"fisrtName middleName laseName:"<<endl;
while(!inFile.eof())
{
getline(inFile, name);
cout << name <<endl;
}
while(!inFile1.eof())
{
getline(inFile1, name);
cout <<"After Altering String Name is: "<<alter_string(name)<<endl;
}
inFile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.