9.6 编程练习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 handiap(golf &g, int hc);
void showgolf(const golf& g);
golf.cpp
#include"stdafx.h"
#include<iostream>
#include<string>
#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 << "输入姓名" << ":";
string strTmp;
getline(cin, strTmp);
if ("" == strTmp)
return 0;
strcpy(g.fullname, strTmp.c_str());//注意strcpy函数返回类型为指针,参数也为指针类型
cout << "输入等级";
int n;
cin >> n;
cin.get();
if (!n)
{
return 0;
}
g.handicap = n;
return 1;
}
void handicap(golf &g, int hc)
{
g.handicap = hc;
}
void showgolf(const golf& g)
{
cout << g.fullname << '\t' << g.handicap;
}
main.cpp
#include "stdafx.h"
#include<iostream>
#include<string>
#include"golf.h"
using namespace std;
int main()
{
const unsigned k_size = 4;
golf golfers[k_size];
unsigned numGolders = 0;
while (numGolders < k_size&&setgolf(golfers[numGolders]))
++numGolders;
for (unsigned i = 0; i < numGolders; ++i){
showgolf(golfers[i]);
cout << endl;
}
}
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 handiap(golf &g, int hc);
void showgolf(const golf& g);
golf.cpp
#include"stdafx.h"
#include<iostream>
#include<string>
#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 << "输入姓名" << ":";
string strTmp;
getline(cin, strTmp);
if ("" == strTmp)
return 0;
strcpy(g.fullname, strTmp.c_str());//注意strcpy函数返回类型为指针,参数也为指针类型
cout << "输入等级";
int n;
cin >> n;
cin.get();
if (!n)
{
return 0;
}
g.handicap = n;
return 1;
}
void handicap(golf &g, int hc)
{
g.handicap = hc;
}
void showgolf(const golf& g)
{
cout << g.fullname << '\t' << g.handicap;
}
main.cpp
#include "stdafx.h"
#include<iostream>
#include<string>
#include"golf.h"
using namespace std;
int main()
{
const unsigned k_size = 4;
golf golfers[k_size];
unsigned numGolders = 0;
while (numGolders < k_size&&setgolf(golfers[numGolders]))
++numGolders;
for (unsigned i = 0; i < numGolders; ++i){
showgolf(golfers[i]);
cout << endl;
}
}