C++ Primer第九章课后编程题

1、

代码:
头文件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);
golf.cpp代码
#include<iostream>
#include<cstring>
#include "golf.h"
using namespace std;
void setgolf(golf & g, const char * name, int hc)
{
    strcpy(g.fullname, name);
    g.handicap = hc;
}
int setgolf(golf & g)
{
    cout<< "请输入全名: ";
    cin.getline(g.fullname, Len);
    if (g.fullname[0] == '\0')
        return 0;
    cout << "Enter handicap value: ";
    while (!(cin >> g.handicap))
    {
        cin.clear();
        cout << "请输入整数:";
    }
    while (cin.get() != '\n')
        continue;
    return 1;
}
void handicap(golf & g, int hc)
{
    g.handicap = hc;
}
void showgolf(const golf & g)
{
    cout << "Golfer: " << g.fullname << "\n";
    cout << "Handicap: " << g.handicap << "\n\n";
}
const int Mems = 5;
int main()
{
    golf team[Mems];
    cout << "输入 " << Mems << " 球队成员:\n";
    int i;
    for (i=0; i<Mems; i++)
        if (setgolf(team[i]) == 0)
            break;
    for (int j=0; j<i; j++)
        showgolf(team[j]);
    setgolf(team[0], "Fred Norman", 5);
    showgolf(team[0]);
    handicap(team[0], 4);
    showgolf(team[0]);
    return 0;
}
运行结果:


2、修改程序清单9.8:用string对象代替字符数组.这样,该程序将不再需要检查 输入的字符串是否过长,同时可以将输入字符串同字符串""进行比较,比判断是 否为空行
代码:
#include<iostream>
#include<string>
using namespace std;
void strcount(const string &str);
int main()
{
    string input;
    cout << "Enter a line:\n";
    getline(cin, input);
    while ("" != input)
    {
        strcount(input);
        cout << "Enter next line:";
        getline(cin, input);
    }
    cout << "bey!\n";
}
void strcount(const string &str)
{
    cout << "\"" << str << "\": ";
    int count = str.length();
    cout << count << "  characters\n";
}
运行结果:


3、

代码:
#include<iostream>
#include<cstring>
struct chaff
{
    char dross[20];
    int slag;
};
int main()
{
    using std::cout;
    using std::endl;
    chaff *p1;
    int i;
    p1 = new chaff[2];
    std::strcpy(p1[0].dross, "Tiffany Zhao");
    p1[0].slag=13;
    std::strcpy(p1[1].dross, "guugle");
    p1[1].slag=-23;
    for(i=0; i<2; i++)
        cout << p1[i].dross << ": " << p1[i].slag <<endl;
    delete [] p1;
    return 0;
}
运行结果:



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值