Write your question here.
I need to write a constant string function that takes a users first and last name all in one input. Then the user enters another name which replaces the last name and then outputs the new full name. Example:
"Enter full name: John Doe
Enter new last name: Dane
Your new name: John Dane.
The function signature has to be: string swapLastName(const string full_name, const string new_last_name)
I have the code worked out to produce the first name and to recognize a space so as to start the last name (which could be any number of names and spaces). But now I don't know how to grab or identify the last name in the string. I need a code example of how to grab a string after a space or a code example of using two strings on the same input. Or just something.
// Joshua Cisneros
// Assignment 4.3
// Due Date: 2/28/16
// Purpose: Write a function with the signature of string swapLastName(const string full_name, const string new_last_name)
// that function should take in the user's full name (first & last),
// swaps the user's last name with another last name to be
// entered by the user, and returns the user's modified full name to the console.
#include <iostream>
#include<cctype>
using std::cout;
using std::cin; using std::string;
int main()
{
string name;
getline(cin, name);
string first_name(name.size(), ' ');
//to get the first name
for (string::size_type i=0; i!=name.size(); ++i)
{
if (isspace(name[i])) //will check if "i" char of name is space, if yes then break and out of the loop.
break;
first_name[i]= name[i];
}
int ch_cnt=0;
//to get the no. of char in first name
for (string::size_type i=0; i!=first_name.size(); ++i)
{
if (isalnum(first_name[i]))
++ch_cnt;
}
first_name.erase(ch_cnt, first_name.size()); // remove the unnecessary spaces from first name
cout <<first_name <<" ";
return 0;
}