I am trying to print the first, middle, and last names from a text file that is formatted like this:
Doe, John Bob
Young, Tim Joe
Washington, George Peter
Here is the expected output:
First name: John
Middle name: Bob
Last name: Doe
First name: Tim
Middle name: Joe
Last name: Young
First name: George
Middle name: Peter
Last name: Washington
I am able to get the middle name and last name correctly, but when I try to get the first name, it shows that it is the first and middle names. Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Variable for the text file
ifstream infile;
//Opens the text file
infile.open("data.txt");
//Variables for the names
string name;
string lastName;
string firstName;
string middleName;
//Loops through all the names
while(getline(infile, name))
{
//Looks for a comma and space in each name
int comma = name.find(',');
int space = name.find(' ', comma+2);
//Splits the name into first, last, and middle names
lastName = name.substr(0, comma);
firstName = name.substr(comma+2, space);
middleName = name.substr(space+1, 100);
//Prints the names
cout << "First name: " << firstName << endl;
cout << "Middle name: " << middleName << endl;
cout << "Last name: " << lastName << endl;
cout << endl;
}
//closes the text file
infile.close();
return 0;
}//end main
Here is the output I get:
First name: John Bob
Middle name: Bob
Last name: Doe
First name: Tim Joe
Middle name: Joe
Last name: Young
First name: George Peter
Middle name: Peter
Last name: Washington