C++ primer plus第九章练习答案

1.下面是一个头文件:
// golf.h -- for pe9-1.cpp
const int Len = 40;struct_golf
char fullname(Len)
int handicap;
// non-interactive version:// function setsgolf structure toprovided name, handicap// using values passedas arguments to the functionvoid setgolf(golf & g- const_char * name, int hc);
// interactive version:
// function solicits name and handicap from user
// and sets the membersof g to the values entered
// returns 1 if name ss entered,0 if name is empty string
int setgodf (golf w g) ;
//function resets handicap to new valuevoid handicapigolf sg-inthc);
// function displays contents ofgolf structurevoid shgwgolf (const goIf 5 g];
注意到 sctgolf-)被重载,可以这样使用其第一个版本golf amn;
setgolf (ann,"Ann irdfree",24]:
上述函数调用提供了存储在ann 结构中的信息可以这样使用第二个版
golf andy;
setgolf (andy) ;
上述函数将提示用户输入姓名和等级,并将它们存储在 ndy 结构中这个函数可以(但是不一定必须)在内部使用第一个版本。
根据这个头文件,创建一个多文件程序。其中的一个文件名为 golf.cpp,它提供了与头文件中的原型匹配的函数定义;另一个文件应包含 main(),并演示原型化函数的所有特性。例如,包含一个让用户输入的循环,并使用输入的数据来填充一个由 golf 结构组成的数组,数组被填满或用户将高尔夫选手的姓名设置为空字符串时,循环将结束。min( )丽数只使用头文件中原型化的函数来访向golf结构。

#include 
#include "golf.h"
using namespace std;

int main()
{
    int sum = 0;
    golf andy[Len];

    setgolf(andy[0], "Ann Birdfree", 24);
    cout << "Starting output:" << endl;
    showgolf(andy[0]);

    handicap(andy[0], 666);
    cout << "Changing handicap:" << endl;
    showgolf(andy[0]);

    for (int i = 0; i < Len; i++)
    {
        cout << "Please enter andy #" << i + 1 << ": " << endl;
        if (0 == setgolf(andy[i]))
        {
            break;
        }
        ++sum;
    }
    if (sum > 0)
    {
        cout << "Ending output:" << endl;
    }
    for (int i = 0; i < sum; i++)
    {
        showgolf(andy[i]);
    }
    cout << "Bye." << endl;

    return 0;
}
#include 
#include 
#include "golf.h"

void setgolf(golf &g, const char *name, int hc)
{
    strncpy(g.fullname, name, Len);
    g.fullname[Len - 1] = '\0';
    g.handicap = hc;
    return;
}

int setgolf(golf &g)
{
    using std::cin;
    using std::cout;
    cout << "Please enter the fullname(enter to quit): ";
    cin.getline(g.fullname, Len);
    if (0 == strcmp(g.fullname, "\0"))
    {
        return 0;
    }
    cout << "Please enter the handicap: ";
    while (!(cin >> g.handicap))
    {
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "Please enter an number: ";
    }
    cin.get();
    return 1;
}

void handicap(golf &g, int hc)
{
    g.handicap = hc;
}

void showgolf(const golf &g)
{
    std::cout << "Name: " << g.fullname << std::endl;
    std::cout << "Handicap: " << g.handicap << std::endl;
}
#ifndef GOLF_H_
#define GOLF_H_

const int Len = 40;
struct golf
{
    char fullname[Len];
    int handicap;
};

void setgolf(golf &g, const char *name, int hc);

int setgolf(golf &g);

void handicap(golf &g, int hc);

void showgolf(const golf &g);

#endif

2.修改程序清单 9.9:用 string 对象代字符数组。这样,该将再需要查输入的字符是否过长,同时可以将输入字符串同字符串“”进行比较,以判断是否为空行。

#include 
#include 
using namespace std;

void strcount(const string &str);

int main()
{
    string input;

    cout << "Enter a line:\n";
    while (getline(cin, input), input != "")
    {
        strcount(input);
        cout << "Enter next line (empty line to quit):\n";
    }
    cout << "Bye" << endl;

    return 0;
}

void strcount(const string &str)
{
    static int total = 0;

    cout << "\"" << str << "\" contains ";
    total += str.size();
    cout << str.size() << " characters\n";
    cout << total << " characters total\n";
}

3.下面是一个结构声明:

struct chaff
char dross[20]:
int slag;
编写一个程序,使用定位 ncw 运算符将一个包含两个这种结构的数组放在一个缓冲区中。然后,给结构的成员赋值(对于 char 数组,使用函数 strpy())并使用一个循环来显示内容。一种方法是像程序清单9.10 那样将一个静态数组用作缓冲区:另一种方法是使用常规 new 运算符来分配缓冲区。

#include 
#include 
#include 

const int BUF = 512;
static char buffer[BUF];
struct chaff
{
    char dross[20];
    int slag;
};

int main()
{
    using namespace std;
    char temp[20];
    chaff *str = new (buffer) chaff[2];
    for (int i = 0; i < 2; i++)
    {
        cout << "Enter the content of dross #" << i + 1 << ": ";
        cin.getline(temp, 20);
        strcpy(str[i].dross, temp);
        cout << "Enter the content of slag #" << i + 1 << ": ";
        while (!(cin >> str[i].slag))
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number: ";
        }
        cin.get();
    }
    for (int i = 0; i < 2; i++)
    {
        cout << "Chaff #" << i + 1 << ": " << endl;
        cout << "Dross: " << str[i].dross << endl;
        cout << "Slag: " << str[i].slag << endl;
    }

    return 0;
}

4.请基于下面这个名称空间编写一个由3个文件组成的程序
namespace SALES
const int QUARTERS = 4:
struct Sales
double sales[QUAATERS]
double average;
double max;
double min;
// copies the lesser of i or n items from the array ar

// to the sales member of s and computes and stores the

// average, maximum, and minimum values of the entered items;

// remaining elements of gales, if any, get to 0void setSales(Sales 点 s, const double ar[], int nl;

// gathers sales for 4 quarters interactively. gtores them

// in the sales member of s and computes and stores the

// average,maximum, and mimimum welues
void setSales(Sales 5 s];
// display all information in strucr.ure s
void showSalesiconst Sales 点 s]:
第一个文件是一个头文件,其中包含名称空间:第二个文件是一个源代码文件,它对这个名称空间进行扩展,以提供这三个函数的定义:第三个文件声明两个 Sals 对象,并使用 setSales()的交互式版本为一个结构提供值,然后使用 setSales()的交式版本为另一个结构提供值,另外它还使用 showSales()来显示这两个结构的内容。

#include 
#include "sales.h"

int main()
{
    SALES::Sales objects[2];
    const double temp[4] = {1.0, 2.0, 3.0, 4.0};

    SALES::setSales(objects[0]);
    SALES::setSales(objects[1], temp, 4);
    SALES::showSales(objects[0]);
    SALES::showSales(objects[1]);
    std::cout << "Bye." << std::endl;

    return 0;
}
#include 
#include "sales.h"

namespace SALES
{
    void setSales(Sales &s, const double ar[], int n)
    {
        double total = ar[0], maxv = ar[0], minv = ar[0];
        for (int i = 1; i < n; i++)
        {
            s.sales[i] = ar[i], total += ar[i];
            maxv = ar[i] > maxv ? ar[i] : maxv;
            minv = ar[i] < minv ? ar[i] : minv;
        }
        s.min = minv, s.max = maxv, s.average = total / n;
    }
    void setSales(Sales &s)
    {
        using namespace std;
        int len;
        cout << "Enter the length of sales(<= 4 and > 0): ";
        while (!(cin >> len) || len > 4 || len <= 0)
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number(<= 4 and > 0): ";
        }
        double *temp = new double[len];
        cout << "Please enter the sales:" << endl;
        for (int i = 0; i < len; i++)
        {
            cout << "Please enter the content #" << i + 1 << ": ";
            while (!(cin >> temp[i]))
            {
                cin.clear();
                while (cin.get() != '\n')
                    continue;
                cout << "Please enter a number: ";
            }
        }
        setSales(s, temp, len);
        delete[] temp;
    }
    void showSales(const Sales &s)
    {
        std::cout << "Sales average: " << s.average << std::endl;
        std::cout << "Sales max: " << s.max << std::endl;
        std::cout << "Sales min: " << s.min << std::endl;
    }
}
#ifndef SALES_H_
#define SALES_H_

namespace SALES
{
    const int QUARTERS = 4;
    struct Sales
    {
        double sales[QUARTERS];
        double average;
        double max;
        double min;
    };
    void setSales(Sales &s, const double ar[], int n);
    void setSales(Sales &s);
    void showSales(const Sales &s);
}

#endif

你可能感兴趣的:(c++,primer,plus阅读心得,c++,c++,学习,源码,分享)