I am a newbie to C++ programming and am currently reading this book called Jumping to C++ by Alex Allain. I have finished the pointers chapter and I am doing the exercises at the end of the chapter.
The following paragraphs are the exercises and included are my own solutions:
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!)
// pointersExercise01.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
void printName(string *pointFirstName, string *pointLastName){
cout << endl << "Hello " << *pointFirstName << " " << *pointLastName;
}
void printName(string &pointFirstName, string &pointLastName){
cout << endl << "Hi " << pointFirstName << " " << pointLastName;
}
int _tmain(int argc, _TCHAR* argv[])
{
string firstName, lastName;
cout << "Enter First Name ";
cin >> firstName;
cout << endl << "Enter Last Name ";
cin >> lastName;
/*FUNCTION POINTERS*/
printName(&firstName, &lastName); // print out using pointers
/*REFERENCE POINTERS*/
printName(firstName, lastName);
system("pause");
return 0;
}
The next exercise is to modify the program I wrote for exercise 1 so that instead of always prompting the user for a last name, it does so only if the caller passes in a NULL pointer for the last name.
// nullPointerExercise3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
void userNames(string *pointerFirstName, string *pointerLastName){
string firstN = *pointerFirstName;
string LastN = *pointerLastName;
bool flag;
do{
if(LastN == "NULL" ){
cout << "Again what is your last name? ";
cin >> LastN;
flag = true;
}else{
flag = false;
}
}while(flag != false);
}
int _tmain(int argc, _TCHAR* argv[])
{
string firstName, lastName;
cout << "FIRSTNAME: ";
cin >> firstName;
cout << "\n" << "LASTNAME: ";
cin >> lastName;
userNames(&firstName, &lastName);
system("pause");
return 0;
}
If possible, I'd like to know if I did right for both of the exercise and if I am in the right direction. Comments and tips will be helpful.