C++primer第八章课后变成练习的小问题

3:toupper()是将小写转换成大写的函数,但是,该函数只接受单个字符,如果使用string类型字符串时,需要用循环一个字符一个字符的转换,第三题答案

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

void change(string &a);
void show(const string &a);
int main()
{
	cout<<"Enter a string(q to quit):";
	string s;
	
	while(cin>>s&&s!="q")
	{
		change(s);
		show(s);
		cout<<"Next string(q to quit):";
		
		
	}
	cout<<"Bye."<<endl;

	cin.get();
	cin.get();
	return 0;
}

void change(string &a)
{
	int size=a.size();
	for(int i=0;i<size;i++)
	{
		a[i]=toupper(a[i]);
	}
}
void show(const string &a)
{
	cout<<a<<endl;
}
第二题中,设计一个函数,通过调用结构体对其赋值时,要将结构体的引用一起调用,例如:
#include<iostream>

struct CandyBar
{
	char name[40];
	double height;
	int hot;
};

void input(CandyBar &a1,const char *p="Milennium",const double d=2.85,const int i=350)//这个地方如果没有前面的引用参数的话,后面对结构体的赋值则不能通过,
{
	using namespace std;
	a1.hot=i;
	strcpy_s(a1.name,strlen(p)+1,p);
	a1.height=d;
}

void show(const CandyBar &a)
{
	using namespace std;
	cout<<"name:"<<a.name<<endl;
	cout<<"weight:"<<a.height<<endl;
	cout<<"hot:"<<a.hot<<endl;
}

int main()
{
	using namespace std;
	CandyBar a;
	input(a);
	show(a);
	input(a,"waaa",2.5,1);
	show(a);

	cin.get();
	return 0;
}

第六题,在模板中,定义时各个模板的名字应该一样,即模板重载:
#include<iostream>
using namespace std;

template<typename T1,typename T2>
T1 Max(T1 *a,T2 b)
{
	T1 max=a[1];
	for(int i=1;i<b;i++)
	{
		if(max<a[i])
		{
			max=a[i];
		}
	}
	return max;
}

template <> char * Max<char *> (char *ps[],int n)
{
	size_t si1,si2;
	for(int i=0;i<n;i++)
	{
		cout<<(int *)ps[i]<<endl;
		if((si1=strlen(ps[0]))<(si2=strlen(ps[i])))
		{
			
			ps[0]=ps[i];
		}
	}
	return ps[0];
}

int main()
{
	int arr1[6]={2,3,5,3,1,5};
	int size1,size2;
	size1=sizeof(arr1)/sizeof(int);
	int big1=Max(arr1,size1);
	cout<<"the bigger of int is:"<<big1<<endl;
	double arr2[4]={3.2,5.3,2.1,3.2};
	size2=sizeof(arr2)/sizeof(double);
	double big2=Max(arr2,size2);
	cout<<"the bigger of double is:"<<big2<<endl;

	char *arr3[3]={"aaa","bbb","ddddd"};
	cout<<"max string address:"<<(int *)Max(arr3,3)<<endl;
	cin.get();
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值