1、接收字符串,根据被调用次数打印字符串
# include<iostream>
# include<string>
using namespace std;
void fun(string tr,int & c,int num=0)//默认参数的设置必须在参数列表的最右端
{
c++;
for(int i=0; i<c; i++)
cout<<tr<<endl;
return;
}
int main(void)
{
string str="haha";
int c = 0;//计数fun()被调次数,初始为零
fun(str,c,1);
fun(str,c,1);//
return 0;
}
2、默认参数的设置
# include<iostream>
# include<string>
using namespace std;
struct CandyBar
{
char * name;
double weight;
int heat;
};
void fun(CandyBar & brand,char * nam ="Millennium",const double wei =2.85,const int hea = 350)
{
brand.name = nam;
brand.weight = wei;
brand.heat = hea;
cout<<brand.name<<"\t"<<brand.weight<<"\t"<<brand.heat<<endl;
return ;
}
int main(void)
{
CandyBar a;
fun(a,"haha",2.1,3);
return 0;
}
3、小写转换成大写(toupper)
<pre class="cpp" name="code"># include<iostream>
# include<string>
# include<cctype>
using namespace std;
void fun(string & a)
{
for(int i=0; i<a.size(); i++) //string 类定义的字符串是没有‘\0’结束标志的
{
a[i] = toupper(a[i]); //toupper是定义在头文件cctype中的小写字母转大写字母的函数
}
return ;
}
int main(void)
{
string str;
cin>>str;
string temp;
fun(str);
cout<<str<<endl;
while(1)
{
cout<<"Next string (q to quit):"<<endl;
cin>>temp;
if(temp == "q")
{
cout<<"Bye"<<endl;
break;
}
else
{
fun(temp);
cout<<temp<<endl;
}
}
return 0;
}
4、
# include<iostream>
using namespace std;
# include<cstring>
struct stringy
{
char * str;
int ct;
};
void set(stringy & b, char *);
void show(const stringy b , int n =1);
void show(const char * t, int n=1);
int main()
{
stringy beany;
char testing[]="Reality isn't what it used to be.";
set(beany,testing);
show(beany);
show(beany,2);
testing[0]='D';
testing[1]='u';
show(testing);
show(testing,3);
show("Done!");
return 0;
}
void set(stringy & b, char * t)
{
b.str = new char [strlen(t)];
b.str = t;
b.ct = strlen(t);
return ;
}
void show(stringy b,int n)
{
for(int i=0; i<n; i++)
{
cout<<b.str<<endl;
}
return ;
}
void show(const char * t,int n)
{
for(int i=0; i<n; i++)
{
cout<<t<<endl;
}
return ;
}
5、模版函数
# include <iostream>
using namespace std;
template <typename T>
T max5(T a[]);
int main()
{
int a1[5] = {1,2,3,4,5};
double a2[5] = {1.1,2.2,3.3,4.4,5.5};
cout<<"int类型最大值:"<<max5(a1)<<endl;
cout<<"double类型最大值:"<<max5(a2)<<endl;
return 0;
}
template <typename T>
T max5(T a[])
{
T max;
max =a[0];
for(int i=1; i<5; i++)
{
if(max<a[i])
max=a[i];
else
;
}
return max;
}
6、