Do Programming Exercise 1 from Chapter 9 but replace the code shown there with an appropriate golf

Question:

Do Programming Exercise 1 from Chapter 9 but replace the code shown there with an appropriate golf class declaration. Replace setgolf(golf &, const char*, int) with a constructor with the appropriate argument for providing initial values. Retain the interactive version of setgolf() but implement it by using the constructor. (For example, for the code for setgolf(), obtain the data, pass the data to the constructor to create a temporary object, and assign the temporary object to the invoking object, which is *this.)

*/
#include <iostream>
#include "golf.h"

const int NUM_GOLF = 10;

int main() {
    using namespace std;
    using chp10::Golf;

    Golf golfers[NUM_GOLF];

    int numCollected = 0;

    for (int i = 0; i < NUM_GOLF; i++) {
        cout << "Golfer #" << i + 1 << endl;

        if (!golfers[i].setgolf()) {
            break;
        }

        numCollected++;
    }

    cout << numCollected << " golfers were entered." << endl;

    for (int i = 0; i < numCollected; i++) {
        golfers[i].showgolf();
    }

    Golf tiger("Tiger Woods", 24);

    tiger.showgolf();
    tiger.handicap(25);
    tiger.showgolf();

    return 0;
}


/*
 * golf.h
 *
 *  Created on: Jan 23, 2014
 *      Author:
 */

#ifndef GOLF_H_
#define GOLF_H_

namespace chp10 {

class Golf {
    static const int Len = 40;
    char fullname[Len];
    int hcap;

public:
    Golf();
    Golf(const char * name, int hc);
    int setgolf();
    void handicap(int hc);
    void showgolf();
};

}

#endif /* GOLF_H_ */


/*
 * golf.cpp
 *
 *  Created on: Jan 23, 2014
 *      Author:
 */
#include "golf.h"
#include <cstring>
#include <iostream>

namespace chp10 {
    Golf::Golf(){
        strcpy(this->fullname, "--Blank--");
        this->hcap = 0;
    }
    Golf::Golf(const char * name, int hc) {
        strcpy(this->fullname, name);
        this->hcap = hc;
    }

    int Golf::setgolf() {
        char fName[Len];
        int hCap;

        std::cout << "Enter name: ";
        std::cin.getline(fName, Len);

        std::cout << "Enter handicap: ";
        (std::cin >> hCap).get();

        *this = Golf(fName, hCap);

        return strlen(this->fullname) == 0 ? 0 : 1;
    }

    void Golf::handicap(int hc) {
        this->hcap = hc;
    }

    void Golf::showgolf() {
        std::cout << "Name: " << this->fullname << std::endl;
        std::cout << "Handicap: " << this->hcap << std::endl;
    }
}

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  book-img-for-question

C++ Primer Plus

ISBN: 9780321776402

6th Edition

Authors: Stephen Prata

Question Posted: