1 Replies - 329 Views - Last Post: 02 September 2013 - 06:54 AM Rate Topic: -----

#1 The System  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 01-September 13

A bit of explanation needed for "Jumping into c++" Ch 13 probl

Posted 02 September 2013 - 06:45 AM

Hello,
I have been reading c++ ebook "Jumping into c++" and there is a practice problem that I donīt understand quite well from chapter 13(Using Pointers).
Could someone simplify the question or point me in a good direction?(Not asking for source code)
Here is the problem.

1. 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 the swap function(Function was written by the author of the book, Alex Allain)
#include <iostream>
using namespace std;
void swap1 (int left, int right)
{
int temp;
temp = left;
left = right;
right = temp;
}
void swap2 (int *p_left, int *p_right)
{
int temp = *p_left;
*p_left = *p_right;
*p_right = temp;
}
int main ()
{
int x = 1, y = 2;
swap1( x, y );
cout << x << " " << y << '\n';
swap2( & x, & y );
cout << x << " " << y << '\n';
}


Thank you.

Is This A Good Question/Topic? 0
  • +

Replies To: A bit of explanation needed for "Jumping into c++" Ch 13 probl

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2009
  • View blog
  • Posts: 3,032
  • Joined: 21-June 11

Re: A bit of explanation needed for "Jumping into c++" Ch 13 probl

Posted 02 September 2013 - 06:54 AM

You're supposed to write a function readNames that can be used like this:

#include <iostream>
#include <string>

using namespace std;

// Definition for readNames goes here

int main() {
    string firstName, lastName;
    readNames(&firstName, &lastName);
    cout << "Hello, " << firstName << " " << lastName << endl;
}



Then you're supposed to define a second function that does the same thing, but without needing the ampersands when calling the function.

PS: The swap1 function's signature in the code you posted should be void swap1 (int& left, int& right) (notice the ampersands) unless it's an example of how not to define a swap function.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1