Recently, I have been learning C++ using the book "Jumping Into C++" and I had a question about one of the exercises. The exercise is as follows:
Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should return both values to the caller via additional pointer (or reference) parameters that are passed to the function. Try doing this first with pointers and then with references. (Hint: the function signature will look be similar to the swap function from earlier!)
Here is what my solution looks like:
Code:
#include <iostream>
#include <string>
using namespace std;
void nameSwap(string *pFname, string *pLname);
int main(){
string firstName;
string lastName;
cout << "Please enter your first name: ";
getline(cin, firstName);
cout << "Please enter your last name: ";
getline(cin, lastName);
nameSwap(&firstName, &lastName);
cout << "Nice to meet you " << lastName << " " << firstName << "!" << "\n";
return 0;
}
void nameSwap(string *pFname, string *pLname){
string temp = *pFname;
*pFname = *pLname;
*pLname = temp;
}
When I run the code it works but I'm not sure if I'm doing what the problem is asking. It doesn't ask to swap the names, so that's why I wrote the nameSwap function like that. Any help is greatly appreciated. Thanks!