Need Some Help Please!!
Apr 2, 2013 at 6:22am UTC
I"m given a file with a name in the format of last name, first name middle name. I need to output the data in the format of first name middle name last name. Some names don't have a middle name. I've gotten to display in the correct order but on each line the names are there twice. Is there anyway to get the names to display once?
these are the names I'm using
Jones, Tommy Eddie
Smith, Andrew
Adkins, Terry Brooke
Sellers, Kathy Kitty
Adams, Ethan
This is the code that I have so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string firstName, middleName, lastName;
string line;
ifstream inFile;
ofstream outFile;
inFile.open("Name.txt" );
outFile.open("NewName.txt" );
while (getline(inFile, line))
{
int comma = line.find(',' );
int length = line.length();
lastName = line.substr(0, comma);
int space_after_Name = line.find(',' , comma + 2);
if (space_after_Name !=1)
{
firstName = line.substr(comma+2,
space_after_Name - comma -2);
middleName = line.substr(space_after_Name +1, length);
outFile << firstName << " " << middleName << " " ;
}
outFile << lastName << endl;
}
return 0;
}
Apr 2, 2013 at 8:26am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include<iostream>
#include <sstream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string firstName, middleName, lastName;
string line;
ifstream inFile( "Name.txt" ) ;
ofstream outFile( "NewName.txt" ) ;
while (getline(inFile, line))
{
std::istringstream is(line) ;
std::getline(is, lastName, ',' ) ;
is >> firstName ;
bool isMiddle = (is >> middleName) ;
outFile << firstName << ' ' ;
if ( isMiddle )
outFile << middleName << ' ' ;
outFile << lastName << '\n' ;
}
return 0;
}
Topic archived. No new replies allowed.