例5.11 输入3个字符串,要求将字母按由小到大的顺序输出。
#include <iostream>
#include <string>
using namespace std;
int main( )
{string string1,string2,string3,temp;
cout<<″please input three strings:″; //这是对用户输入的提示
cin>>string1>>string2>>string3; //输入3个字符串
if(string2>string3) {temp=string2;string2=string3;string3=temp;}
//使串2≤串3
if(string1<=string2) cout<<string1<<″ ″<<string2<<″ ″<<string3<<endl;
//如果串1≤串2,则串1≤串2≤串3
else if(string1<=string3) cout<<string2<<″ ″<<string1<<″ ″<<string3<<endl;
//如果串1>串2,且串1≤串3,则串2<串1≤串3
else cout<<string2<<″ ″<<string3<<″ ″<<string1<<endl;
//如果串1>串2,且串1>串3,则串2<串3<串1
}
运行情况如下:
please input three strings: China U.S.A. Germany↙
China Germany U.S.A.
例5.12 一个班有n个学生,需要把每个学生的简单材料(姓名和学号)输入计算机保存。然后可以通过输入某一学生的姓名查找其有关资料。当输入一个姓名后,程序就查找该班中有无此学生,如果有,则输出他的姓名和学号,如果查不到,则输出“本班无此人”。
为解此问题,可以分别编写两个函数,函数input_data用来输入n个学生的姓名和学号,函数search用来查找要找的学生是否在本班。
程序可编写如下:
#include <iostream>
#include <string>
using namespace std;
string name[50],num[50]; //定义两个字符串数组,分别存放姓名和学号
int n; //n是实际的学生数
int main( )
{void input_data( ); //函数声明
void search(string find_name); //函数声明
string find_name; //定义字符串变量,find_name是要找的学生
cout<<″please input number of this class:″; //输入提示: 请输入本班学生的人数
cin>>n; //输入学生数
input_data( ); //调用input_data函数,输入学生数据
cout<<″please input name you want find:″; //输入提示: 请输入你要找的学生名
cin>>find_name; //输入要找的学生的姓名
search(find_name); //调用search函数,寻找该学生姓名
return 0;
}
void input_data( ) //函数首部
{int i;
for (i=0;i<n;i++)
{cout<<″input name and NO. of student ″<<i+1<<″:″;
//输入提示
cin>>name[i]>>num[i];} //输入n个学生的姓名和学号
}
void search(string find_name) //函数首部
{int i;
bool flag=false;
for(i=0;i<n;i++)
if(name[i]==find_name) //如果要找的姓名与本班某一学生姓名相同
{ cout<<name[i]<<″ has been found, his number is ″ <<num[i]<<endl;
//输出姓名与学号
flag=true;
break;
}
if(flag==false) cout<<″can′t find this name″;//如找不到,输出“找不到”的信息
}
运行情况如下:
please input number of this class:5↙
input name and number of student 1:Li 1001↙
input name and number of student 2:Zhang 1002↙
input name and number of student 3:Wang 1003↙
input name and number of student 4:Tan 1004↙
input name and number of student 5:Fun 1005↙
please input name you want find:Wang↙
Wang has been found,his number is 1003
请考虑:
(1) 程序第3行定义全局变量时,数组的大小不指定为50,而用变量n,即string name[n],num[n];n在运行时输入,行不行?为什么?
(2) search函数for循环中最后有一个break语句,它起什么作用?不要行不行?
(3) 如果不使用全局变量,把变量n和数组name,num都作为局部变量,通过虚实结合的方法在函数间传递数据,这样行不行?请思考并上机试一下。
通过以上两个例子可以看到,用string定义字符串变量,简化了操作,把原来复杂的问题简单化了,这是C++对C的一个发展。
归纳起来,C++对字符串的处理有两种方法: 一种是用字符数组的方法,这是C语言采取的方法, 一般称为Cstring方法;一种是用string类定义字符串变量,称为string方法。显然,string方法概念清楚,使用方便,最好采用这种方法。C++保留C-string方法主要是为了与C兼容,使以前用C写的程序能用于C++环境。
评论