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;
}