How to print only first and last words of a string

I am trying to create a program that will allow a user to input their full name (middle name included), but then will output their first and last name only and separately. Additionally, the program will tell them the number of characters for their name and spit their full name back out to them. The desired output is as follows:

Enter name: Grace B. Hopper
Number of characters: 15
First name: Grace
Last name: Hopper

I have had success accomplishing the first two parts of the output, but cannot seem to figure out how to separate and print the first and last name of the input. Would I use a find function for this? Can I print only the first and last words of a string? How do I go about this? Below is my program thus far:

int main()
string firstName;
string lastName;
string fullName;

cout << "Enter name: ";

getline(cin, firstName, ' ');
getline(cin, lastName);
fullName = firstName + ' ' + lastName;

cout << "Number of characters: " << fullName.length() << endl;

cout << "First name: " << firstName << endl;
cout << "Last name: " << lastName << endl;

return 0;
You'll have to use find and substr functions from the string library.

You will have to find the white space in the last name and then you'll have to make a substr of everything after the space.
getline( cin, fullName );
to get the whole name. Otherwise the number of characters may be wrong, and you can't guarantee the number of intermediate initials.

Then put it in a stringstream and keep reading it into a lastName variable. When you get the last possible read, lastName will be the last white-space-separated item:
   stringstream ss( fullName );
   ss >> firstName;
   while ( ss >> lastName );  // Empty loop; afterwards, lastName will be the last legitimate read 

If you don't need to slice up a string here's an easy way

        std::string first, middle, last;
	std::cin >> first >> middle >> last;

	std::cout << << "Enter name: " << first << ' ' << middle << ' ' << last << std::endl;
	std::string full = first + middle + last;
	std::cout << "Number of characters: " << full.size() << std::endl;
	std::cout << "First name: " << first << std::endl;
	std::cout << "Last name: " << last << std::endl;
Last edited on
Registered users can post here. Sign in or register to post.