Extracting only first name from string

My input file is suppose to look like this
Fahman, Ray Alph
.
Last name, First name optional middle name
is how the input should be like. I have already made the following code that gives me a correct first name. My question is there any other efficient way I can extract the first name out of my file. Just looking for other ideas so I can have more tools and thoughts for my other assignment. Thanks for reading guys!

1
2
3
4
5
6
7
8
9
10
11
12
13
  string firstname(string name)
{
	//find the length of name
	int length=name.length();
	string::size_type pos;
	
	pos=name.find(',');[output][/output]

	// extract the first name
	return name.substr(pos+1, (name.find_last_of(' ')-(pos+1)));

	
}
You could use a stringstream
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
#include <iostream>
#include <sstream>
#include <string>
using namespace std;


int main()
{
	string input = "Fahman, Ray Alph";
	stringstream ss(input);
	string firstName = "";
	string secondName = "";
	string middleName = "";

	getline(ss, firstName, ',');
	ss >> secondName;

	cout << "firstName: " << firstName << endl;
	cout << "secondName: " << secondName << endl;

	if (ss >> middleName)
		cout << "MiddleName: " <<  middleName << endl;


	cin.ignore();
	return 0;
}
Topic archived. No new replies allowed.