In: Computer Science
By using the string function find to find the index of a space; the function length to find the length of the string; and the function substr from a file form firstname, middlename, and lastname to lastname, middlename, and first name. Please help me this is c++ thank you
Answer:
Note: Please make a file of name test.txt and store in the D drive or if you store at another place then change the PATH = "D:\test.txt"; in the given program to your's location.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string PATH = "D:\test.txt";
string alterName(string fullName)
{
string first_Name = "", middle_Name = "", last_Name =
"";
int comma_index = fullName.find(',', 0);
last_Name = fullName.substr(0, comma_index);
fullName = fullName.substr(comma_index + 2);
int space_index = fullName.find(' ', 0);
first_Name = fullName.substr(0, space_index);
if (space_index != -1)
{
middle_Name =
fullName.substr(space_index + 1);
}
string alteredName = first_Name + " ";
if (!middle_Name.empty())
{
alteredName += middle_Name + "
";
}
alteredName += last_Name;
return alteredName;
}
int main()
{
ifstream name_file;
name_file.open(PATH.c_str());
while (name_file.good()) {
string fullName;
getline(name_file, fullName);
string name =
alterName(fullName);
cout << name <<
endl;
}
getchar();
}
Output:
Please give thumbsup, if you like it. Thanks.