C++输出三个字符窜要求按字母由小到大或由大到小输出

我要程序啊~~~~~~~~~~~~

这里有两段代码,都是可行的。
代码是按从小到大排序的,输出顺序或者排序的顺序楼主可以根据需要自己修改。
代码1:
#include <iostream>
#include <cstring>
/*包含这个头文件是因为要用到函数strcmp(const char*, const char*),
它是用来按字典序比较两个字符数组大小的。若前者大,返回值为正;
若后者大,返回值为负;若相等,返回值为0.可以理解为前者减后者做差,
这样好记.
strcpy(const char*, const char*),将后面一个数组的内容复制给前面一个
*/
using namespace std;
const int Len = 100;
void swap_ch(char *a, char *b)
{
char temp[Len];
strcpy(temp,a);
strcpy(a,b);
strcpy(b,temp);
}
int main()
{
char a[Len],b[Len],c[Len];
cin >> a >> b >> c;
if(strcmp(a,b)>0)
swap_ch(a,b);
if(strcmp(a,c)>0)
swap_ch(a,c);
if(strcmp(b,c)>0)
swap_ch(b,c);
cout << a << endl << b << endl << c;
return 0;
}

代码2:
#include <iostream>
#include <string>
/*下面这个是用C++里的类string做的
string类型的对象可以直接用>,<,=来
根据字典序判断字符串大小。这里涉及
到重载的概念,楼主可以上网了解一下*/
using namespace std;
void swap_str(string x, string y)
{
string temp;
temp=x;
x=y;
y=temp;
}
int main()
{
string a,b,c;
cin >> a >> b >> c;
if(a>b) swap_str(a,b);
if(a>c) swap_str(a,c);
if(b>c) swap_str(b,c);
cout << a << endl << b << endl << c;
return 0;
}
望楼主采纳
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-06-10
c++里面字符可以直接用比较数值的方法比较的。如:
i='a';j='b'
那么i-j<0这个表达式是成立的。
第2个回答  2011-06-10
#include <iostream>
#include <string>
using namespace std;
void output1(char* ch); //按字母由小到大
void output2(char* ch); //按字母由大到小
int main()
{

char* ch1="you are very pretty!";
cout<<ch1<<endl;
output1(ch1);
output2(ch1);
}
void output1(char* ch)
{
string text=ch;
int length=text.length();
for(int i=0;i<length;i++)
{
for(int j=i+1;j<length;j++)
{
char str;
if(text[i]>text[j])
{
str=text[i];
text[i]=text[j];
text[j]=str;
}
}
}
cout<<"由小到大排列为: ";
for(int m=0;m<length;m++)
{
if(isalpha(text[m]))
{
cout<<text[m];
}
}
cout<<endl;
}
void output2(char* ch)
{
string text=ch;
int length=text.length();
for(int i=0;i<length;i++)
{
for(int j=i+1;j<length;j++)
{
char str;
if(text[i]<text[j])
{
str=text[i];
text[i]=text[j];
text[j]=str;
}
}
}
cout<<"由大到小排列为: ";
for(int m=0;m<length;m++)
{
if(isalpha(text[m]))
{
cout<<text[m];
}
}
cout<<endl;
}
第3个回答  2011-06-11
怕你没学了排序,就用最简单的if,else分支语句做的!!自己仔细看看!!

#include<iostream>
using namespace std;
#include<cstring>
char *ch[4];
void Com(char a[],char b[],char c[])
{
if(strcmp(a,b)>0)
{
if(strcmp(b,c)>0)

else
{
if(strcmp(a,c)>0)

else

}
}
else
{
if(strcmp(a,c)>0)

else
{
if(strcmp(b,c)>0)

else

}
}
}
int main()
{
char a[20],b[20],c[20];
int i;
while(cin>>a>>b>>c)
{
Com(a,b,c);
for(i=0;i<=2;i++)
cout<<ch[i]<<" ";
cout<<endl;
}
return 0;
}
相似回答