C++ Primer Plus(第六版)中文版编程练习答案

49 C++ Primer Plus(第六版)第八章 编程练习答案

1

#include<iostream>
#include<string>
using namespace std;

int time = 0;

//void show_String(const string* s, int n = 1);

void show_String(const char * s, int n = 1);

int main()
{
   
	/*string s1 = "Happy every day!";
	string* p = &s1;*/

	const char* p = "Happy every day!";

	show_String(p);
	cout << "------------------" << endl;
	show_String(p, 6);
	cout << "------------------" << endl;
	show_String(p, 0);
	cout << "------------------" << endl;
	show_String(p, -6);

	return 0;
}

//void show_String(const string* s, int n)
//{
   
//	if (n == 0)
//	{
   
//		cout << "Error!" << endl;
//	}
//	else
//	{
   
//		time++;
//		for (int i = 0; i < time; i++)
//		{
   
//			cout << *s << endl;
//		}
//	}
//}

void show_String(const char* s, int n)
{
   
	if (n == 0)
	{
   
		cout << "Error!" << endl;
	}
	else
	{
   
		time++;
		for (int i = 0; i < time; i++)
		{
   
			cout << s << endl;
		}
	}
}

2

#include<iostream>
using namespace std;

struct CandyBar
{
   
	char name[40];
	double weight;
	int heat;
};

void set_Candbar(CandyBar& c, const char* p = "Millennium Munch", double d = 2.85, int i = 350);
void show_Candybar(const CandyBar& c);

int main()
{
   
	CandyBar candy;
	set_Candbar(candy);
	show_Candybar(candy);
	cout << "------------------" << endl;
	set_Candbar(candy, "royce", 3, 600);
	show_Candybar(candy);

	return 0;
}

void set_Candbar(CandyBar & c, const char* p, double d, int i)
{
   
	strcpy_s(c.name, p);
	//c.name = p; //不能直接将指针赋值给常量,需要进行字符串复制
	c.weight = d;
	c.heat = i;
}

void show_Candybar(const CandyBar& c)
{
   
	cout << "name: " << c.name << endl
		<< "weight: " << c.weight << endl
		<< "heat: " << c.heat << endl;
}

3

#include<iostream>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值