C ++ Primer Plus 第六版 第九章编程练习答案

2.修改程序清单9.9,用string对象代替字符数组。这样,该程序将不再需要检查输入的字符串是否过长,同时可以将输入字符串同字符串""进行比较,以判断是否为空行。 

#include <iostream>
using namespace std;
void strcount ( const string str )
{
	static int total = 0;
	int count = 0, i = 0;
	cout << "\"" << str << "\" contains ";
	while ( str[i] )
	{
		if ( str[i] == ' ' )
			i++;
		else
		{
			count++;
			i++;
		}
	}
	total += count;
	cout << count << " characters" << endl;
	cout << total << " characters total" << endl;
}

int main()
{
	string str;
	cout << "Enter a line:\n";
	while ( getline ( cin, str ) )
	{
		if ( str == "" ) break;
		strcount ( str );
		cout << "Enter next line:\n";
	}
	cout << "Bye\n";
	return 0;
}


3.下面是一个结构声明:
struct chaff
{
char dross[20];
int flag;
};
编写一个程序,使用定位new运算符将一个包含两个这样的结构的数组放在一个缓冲区中。然后,给结构的成员赋值(对于char数组,使用函数strcpy()),并使用一个循环来显示内容。一种方法是像程序清单9.10那样将一个静态数组用作缓冲区;另一种方法是使用常规new运算符来分配缓冲区。

#include <iostream>
#include <cstring>
using namespace std;
const int ArSize = 100;
struct chaff
{
	char dross[20];
	int slag;
};
char buffer[ArSize];
int main()
{
	chaff ch,*p1;
	char *str=new char[ArSize];
	while ( cin >> str >> ch.slag )
	{
		strcpy ( ch.dross, str );
		p1=new(buffer) chaff;
		*p1=ch;

		cout << "dross : " << p1->dross << endl;
		cout << "slag : " << p1->slag << endl;
	}
	delete []str;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值