C++ Primer Plus第九章课后习题总结

发布于:2025-03-03 ⋅ 阅读:(20) ⋅ 点赞:(0)

1.根据这个头文件:

// golf.h -- for pe9-1.cpp
const int Len = 40;
struct golf
{
       char fullname(Len);
       int handicap;
};
// non-interactive version:
// function sets golf structure to provided name, handicap
// using values passed as arguments to the function
void setgolf(golf & g, const char * name, int hc);
// interactive version:
// function solicits name and handicap from uaer
// and sets the members of g to the valus entered
// returns 1 if name is entered, 0 if name is empty string
int setgolf(golf & g);
// function resets handicap to new value
void handicap(golf & g, int hc);
// function displays  contents of golf structure
void showgolf(const golf &g);

注意到setgolf()被重载,可以这样使用其第一个版本:

golf ann;
setgolf(ann, "Ann Birdfree", 24);

上述函数调用提供了存储在ann结构中的信息。可以这样使用其第二个版本:

golf andy;
setgolf(andy);

上述函数将提示用户输入姓名和等级,并将它们存储在andy结构中。这个函数可以(但是不一定必须)在内部使用第一个版本。

根据这个头文件,创建一个多文件程序。其中的一个文件名为golf.cpp,它提供了与头文件中的原型匹配的函数定义;另一个文件应包含main(),并演示原型化函数的所有特性。例如,包含一个让用户输入的循环,并使用输入的数据来填充一个由golf结构组成的数组,数组被填满或用户将高尔夫选手的姓名设置为空字符串时,循环将结束。main()函数只使用头文件中原型化的函数来访问golf结构。

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

using namespace std;

void setgolf(golf & g, const char * name, int hc){
	strcpy(g.fullname, name);
	g.handicap = hc;
}

int setgolf(golf & g){
	cout << "Fullname:";
	cin.getline(g.fullname, Len);
	if(strlen(g.fullname) == 0){
		return 0;
	}
	cout << "Handicap:";
	cin >> g.handicap;
	cin.get();
	return 1;
}

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

void showgolf(const golf &g){
	cout << "Fullname:" << g.fullname << endl;
	cout << "Handicap:" << g.handicap << endl;
}
#include "golf.h"
#include <iostream>

const int size = 2;
using namespace std;

int main(){
	golf ann;
	setgolf(ann, "Ann Birdfree", 24);
	showgolf(ann);
	
	golf andy;
	if(setgolf(andy) == 1)
		showgolf(andy);
	else{
		setgolf(andy, "Andy Bird", 50);
		handicap(andy, 40);
		showgolf(andy);
	} 
	golf g[size];
	for(int i = 0; i < size; i++){
		cout << "#" << i + 1 << ":" << endl;
		int flag = setgolf(g[i]);
		if(flag == 0){
			setgolf(g[i], "kk", 3);
		}
	}
	for(int i = 0; i < size; i++){
		cout << "#" << i + 1 << "info:" << endl;
		showgolf(g[i]);
	}
	return 0;
}

2.修改程序清单9.9:

//Listing 9.9 static.cpp
// static.cpp -- using a static local variable
#include <iostream>
// constants
const int ArSize = 10;
// function prototype˜
void strcount(const char *str);
int main()
{
    using namespace std;
    char input[ArSize];
    char next;
    cout << "Enter a line:\n";
    cin.get(input, ArSize);
    while (cin)
    {

        cin.get(next);
        while (next != '\n') // string didn't fit!
            cin.get(next);   // dispose of remainder strcount(input);
        cout << "Enter next line (empty line to quit):\n";
        cin.get(input, ArSize);
    }
    cout << "Bye\n";
    return 0;
}
void strcount(const char *str)
{
    using namespace std;
    static int total = 0;
    int count = 0;
    // static local variable // automatic local variable
    cout << "\"" << str << "\" contains ";
    while (*str++) // go to end of string
        count++;
    total += count;
    cout << count << " characters\n";
    cout << total << " characters total\n";
}

用string对象代替字符数组。这样,该程序将不再需要检查输入的字符串是否过长,同时可以将输入字符串同字符串“”进行比较,以判断是否为空行。

 代码如下

//Listing 9.9 static.cpp
// static.cpp -- using a static local variable
#include <iostream>
#include <string>
// constants
//const int ArSize = 10;
// function prototype?
using namespace std;

void strcount(string str);

int main()
{
//    char input[ArSize];
	string input;
    char next;
    cout << "Enter a line:\n";
//    cin.get(input, ArSize);
    getline(cin, input);
	while (input.size())
    {
//        cin.get(next);
//        while (next != '\n') // string didn't fit!
//            cin.get(next);   // dispose of remainder strcount(input);
        strcount(input);
		cout << "Enter next line (empty line to quit):\n";
        getline(cin, input);
    }
    cout << "Bye\n";
    return 0;
}
void strcount(const string str)
{
    using namespace std;
    static int total = 0;
    int count;
    // static local variable // automatic local variable
    cout << "\"" << str << "\" contains ";
    count = str.size();
	total += count;
    cout << count << " characters\n";
    cout << total << " characters total\n";
}

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

struct chaff
{
     char dross[20];
     int slag;
};

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

#include <iostream>
#include <cstring>
using namespace std;
struct chaff
{
     char dross[20];
     int slag;
};
int main(){
	chaff *ch = new chaff[2];
	strcpy(ch[0].dross, "aabbccddee");
	ch[0].slag = 12;
	strcpy(ch[1].dross, "abcde");
	ch[1].slag = 112;
	for(int i = 0; i < 2; i++){
		cout << "#" << i + 1 << ":" << endl;
		cout << "dross:" << ch[i].dross << endl;
		cout << "slag:" << ch[i].slag << endl;
	}
	return 0;
}

4。请基于下面这个名称空间编写一个由3个文件组成的程序:

namespace SALES
{
    const int QUARTERS = 4;
    struct Sales
    {
        double sales [QUARTERS];
        double average;
        double max;
        double min;
    };
    // copies the lesser of 4 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 sales ,if any, set to 0
    void setSales(Sales & s,const double ar[],int n);
    // gathers sales for 4 quarters interactively,stores them
    // in the sales member of s and computes and stores the
    // average,maximum,and minimum values
    void setSales (Sales & s);
    // display all information in structure s
    void showSales(const Sales & s);
}

第一个文件是一个头文件,其中包含名称空间:第二个文件是一个源代码文件,它对这个名称空间进行扩展,以提供这三个函数的定义;第三个文件声明两个Sales对象,并使用setSales()的交互式版本为一个结构提供值,然后使用setSales()的非交互式版本为另一个结构提供值。另外它还使用showSales()来显示这两个结构的内容。

//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);
}
//sales.cpp-----源代码文件
#include "sales.h"

using namespace std;
namespace SALES
{
    void setSales(Sales &s, const double ar[], int n)
    {
        double min = 0, max = 0, sum = 0;
        s.min = s.max = ar[0];
        for (int i = 0; i < n; i++)
        {
            s.sales[i] = ar[i];
            sum += ar[i];
            if (ar[i] > max)
            {
                max = ar[i];
            }
            if (ar[i] < min)
            {
                min = ar[i];
            }
        }
        s.average = sum / n;
    }

    void setSales(Sales &s)
    {
        cout << "Please enter 4 quarters for sales:" << endl;
        cout << "the 1 quarter :";
        cin >> s.sales[0];
        s.min = s.max = s.sales[0];
        for (int i = 1; i < 4; i++)
        {
            cout << "the " << i << " quarter :";
            cin >> s.sales[i];
            if (s.max < s.sales[i])
            {
                s.max = s.sales[i];
            }
            if (s.min > s.sales[i])
            {
                s.min = s.sales[i];
            }
        }
        s.average = (s.sales[0] + s.sales[1] + s.sales[2] + s.sales[3]) / 4;
    }

    void showSales(const Sales &s)
    {
        cout << "Display all information in sales : " << endl;
        cout << "The 4 quarters are $" << s.sales[0] << ", $" << s.sales[1] << ", $" << s.sales[2] << ", $" << s.sales[3] << endl;
        cout << "The average income is $" << s.average << endl;
        cout << "The maximum income is $" << s.max << endl;
        cout << "The minimum income is $" << s.min << endl;
    }
}
//main.cpp
#include "sales.h"
#include <iostream>

using namespace SALES;
int main()
{
    double arr[4] = {3.4, 5.6, 2.5, 6.1};
    Sales s1, s2;
    setSales(s1, arr, 4);
    showSales(s1);
    setSales(s2);
    showSales(s2);
    return 0;
}