C++Primer Plus(第六版) 第八章 第四题

如题

#include<iostream>
using namespace std;
#include<cstring> // for strlen(), strcpy()
struct stringy
{
	char *str; // points to a string
	int ct; // length of string (not counting '\0')
};

// prototypes for set(), show(), and show() go here
void set(stringy & beany, const char *str);
void show(const stringy & beany, const int n = 1);
void show(const char * beany, const int n = 1);

int main()
{
	stringy beany;
	char testing[] = "Reality isn't what it used to be.";

	set(beany, testing); // first argument is a reference
						 // allocates space to hold copy of testing
						 // set str member of beany to point to the
						 // new block, copies testing to new block,
						 // and set ct member of beany
	show(beany); // prints member string once
	show(beany, 2); // prints member string twice
	testing[0] = 'p';
	testing[1] = 'u';
	show(testing); // prints testing string once
	show(testing, 3); // prints testing string theice
	show("Done!");
	cin.get();
	return 0;
}

void set(stringy & beany, const char * str)
{
	beany.ct = strlen(str);
	beany.str = new char[beany.ct + 1];
	strcpy(beany.str, str);
}

void show(const stringy & beany, const int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << beany.str << endl;
	}
}

void show(const char * beany, const int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << beany << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值