Getting first name from string

Input file looks like this
Ray, apple, stewart
Kandi, Ryan Albert
Steve, Jobs


The format of this file would be "lastname, firstname middlename" with the optional midde name. Once I have run my code, this is the following output I get on my console. Please note I just want to display the first and the last name on the screen. yes, I do have to display the middname but I'm working on doing the first and last name right now. so this is the following output got

Apple Ray
Ryan Kandi
 Steve


as you can see I'm only getting the last name displayed for the last data on the file. I have this following code and I know my problem is in that if statement, so can I know how possibly I can correct that. T

this is the function I wrote for obtaining the first name.

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
  string firstname(string name)
{
	//find the length of name
	int length=name.length();
	string::size_type pos;
	string::size_type pos1;
	
	pos=name.find(',');

	//find the last space
	if(name.find_last_of(' ')!=string::npos)
	{
	
	pos1=name.find_last_of(' ')-(pos+1);
	return name.substr(pos+1,pos1);
	}
	else
	{
		char last;
		last=name.back();
		int index=name[last];
		return name.substr(pos+1,index-pos);
	}
	

	
}
I'm assuming that the first line in your input file is incorrect because of the format you say the input is supposed to follow:

fahmankhan75 wrote:
"lastname, firstname middlename"


1
2
3
4
string getFname(const string &name)
{
	return string(name.substr(0, name.find_first_of(',')));		
}


1
2
3
4
string getLname(const string &name)
{
	return string(name.substr(name.find_last_of(' ')));
}
Topic archived. No new replies allowed.