有3个国家名,要求找出按字母排序排在最前面的国家,要求用函数调用
解题思路
此题可以用字符串比较函数处理。比较的结果“最小”的字符串就是按字母顺序排在最前面的字符串。用一个函数smallest_string来找出n个字符串中“最小”的字符串,在main函数中设一个二维的字符数组str,大小为3x30,即有3行30列,每一行可以容纳30个字符。如前所述,可以把str[0],str[1],str[2]看作3个一维字符数组,它们各有30个元素。可以把它们如同一维数组那样处理。用cin分别读入3个字符串。然后调用smallest_string函数,可得到“最小”的字符串,把它放在一维字符数组string中,在函数smallest_string中输出“最小”的字符串。
编写程序:
#include<bits/stdc++.h>
#include<string>
using namespace std;
int main()
{
void smallest_string(char str[][30],int i); //函数声明
int i;
char country_name[3][30];
for(i=0;i<3;i++)
{
cin>>country_name[i]; //输入3个国家名
}
smallest_string(country_name,3); //调用smallest_string函数
return 0;
}
void smallest_string(char str[][30],int n)
{
char string[30];
strcpy(string,str[0]);
for(int i=0;i<n;i++)
{
if(strcmp(str[i],string)<0) //如果str[i]<string
strcpy(string,str[i]); //将str[i]中的字符串复制到string
}
cout<<endl<<"the smallest string is:"<<string; //输出最小的字符串
}