C++Primer Plus第九章内存模型和命名空间练习1,重载的实现。和strcpy_s(),string,getline()的使用

第一题:
//注意到 setgolf()被重载,可以这样使用其第一个版本:golf ann;
//setgolf(ann, “Ann Birdfree”,24);
//上述函数调用提供了存储在 ann 结构中的信息。可以这样使用其第二个版本 :
golf andy;
setgolf(andy);
上述函数将提示用户输入姓名和等级, 并将它们存储在 andy 结构中。这个函数可以(但是不一定必须)在内部使用第一个版本。
根据这个头文件,创建一个多文件程序。其中的一个文件名为golf.cpp,它提供了与头文件中的原型匹配的函数定义;
另一个文件应包含main(),并演示原型化函数的所有特性。例如,包含一个让用户输入的循环,
并使用输入的数据来填充一个由goIf结构组成的数组,数组被填满或用户将高尔夫选手的姓名设置为空字符串时,
循环将结束。main()函数只使用头文件中原型化的函数来访问golf结构。

原文链接:https://blog.csdn.net/zhyjhacker/article/details/139162580
头文件
1,常量和结构体的声明
2,函数的原型的声明

#pragma once
#pragma region 练习1.golf.cpp
//程序清单
//golf.cpp.cpp -- xxx
#if 1
#include<iostream>
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 user
//and sets the members of g to the values entered
//returns l 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);
#endif
#pragma endregion

golf.cpp文件实现具体的函数过程

#pragma region 练习1.golf.cpp
//程序清单
//golf.cpp.cpp -- xxx
#if 1
#include<iostream>
#include"golf.h"
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

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

int setgolf(golf& g)
{

	cout << "请输入你的姓名: ";
	string strname;
	getline(cin, strname);
	if ("" == strname)
		return 0;
	int temp = strlen(strname.c_str());
	cout << temp;
	//这里需要加+1,这是重点,不然会报错的
	strcpy_s(g.fullname, temp+1, strname.c_str());
	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 << endl;
}
#endif
#pragma endregion

4,主函数的的实现

pragma region 练习1.cpp
程序清单
//xxx.cpp -- xxx
#if 1

#include<iostream>
#include"golf.h"
int main(void)
{
	using namespace std;
	const unsigned	ArSize = 4;
	golf gofters[ArSize];
	unsigned numGolfers = 0;
	while (numGolfers < ArSize && setgolf(gofters[numGolfers]))
	{
		numGolfers++;
	}

	for (unsigned i = 0; i < numGolfers; i++)
	{
		showgolf(gofters[i]);
	}
	return 0;
}
#endif
#pragma endregion

这里对函数strcpy_s使用的时候,需要求得字符串的长度,得到长度需要+1,这里不要忘记了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值