输入三个字符串,按照从小到大的顺序输出(c++)

2025-02-24 03:46:22
推荐回答(5个)
回答1:

void main()
{
char st[20],cs[3][20];
int i,j,p;
printf("input three string:\n");
for(i=0;i<3;i++)
gets(cs[i]);
printf("\n");
for(i=0;i<3;i++)
{
p=i;strcpy(st,cs[i]);
for(j=i+1;j<3;j++)
if(strcmp(cs[j],st)<0)
{
p=j;
strcpy(st,cs[j]);
}
if(p!=i)
{
strcpy(st,cs[i]);
strcpy(cs[i],cs[p]);
strcpy(cs[p],st);
}
puts(cs[i]);
}
printf("\n");
getch();
}
这是最基本的方法,当用字符串比较函数strcpy时,需要去交换3个字符串,你也可以用指针做,去交换地址,效率会比这个高。

回答2:

用strcmp函数

回答3:

闲着没事~~~做着玩
#include
#include
using namespace std;

void Swap(string &str1, string &str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
int main(int argc, char* argv[])
{
string str1, str2, str3;
cin>>str1>>str2>>str3;
if (strcmp(str1.c_str(),str2.c_str()) > 0)
{
Swap(str1, str2);
}
if (strcmp(str2.c_str(), str3.c_str()) > 0)
{
if (strcmp(str1.c_str(),str3.c_str()) < 0)
{
Swap(str2, str3);
}else
{
Swap(str1, str3);
Swap(str3, str2);
}
}
cout< return 0;
}

回答4:

用了STL中的vector、sort()函数、iterator

#include
#include
#include
#include
#include

using namespace std;

int main()
{
typedef vector myVector;
typedef istream_iterator IstreamItr;
typedef ostream_iterator OstreamItr;
vector::iterator iter;

myVector str;
string str1;

for(int i=0;i<3;++i)
{
cin>>str1;
str.push_back(str1);
}
sort(str.begin(),str.end());
copy(str.begin(),str.end(),OstreamItr(cout," "));
cout<system("pause");
return 0;
}

回答5:

函数名: strncmp
功 能: 串比较
用 法: int strncmp(char *str1, char *str2, int maxlen);
说明:比较字符串str1和str2的大小,如果str1小于str2,n就<0,反之如果str1大于str2,n就>0,如果str1等于str2,n就=0