帮我做一道编程题!!!高手请进,采纳追加50分!!!

2024-12-19 09:59:39
推荐回答(4个)
回答1:

#include
#include
class compare
{
public:

compare(char * a,char * b,char * c,char * d,char * e);
~compare() {for (int i=0;i<5;i++) delete str[i];}
int ran();
void print();
private:
char *str[5];
};

compare::compare(char * a,char * b,char * c,char * d,char * e)
{
str[0]=new char [strlen(a)+1]; strcpy(str[0],a);
str[1]=new char [strlen(b)+1]; strcpy(str[1],b);
str[2]=new char [strlen(c)+1]; strcpy(str[2],c);
str[3]=new char [strlen(d)+1]; strcpy(str[3],d);
str[4]=new char [strlen(e)+1]; strcpy(str[4],e);
}
int compare::ran()
{
char *s,*t;
for (int i=0;i<4;i++)
for (int j=i+1; j<5;j++)
{
s=str[i]; t=str[j];
while (*s) if (*s==*t) {s++; t++;} else break;
if (*s>*t) {char *temp=str[i];str[i]=str[j];str[j]=temp;}
}
return 1;

}

void compare::print()
{
for(int i=0;i<5;i++)
cout<}

void main()
{
char a[5][100];
cout<<"请输入5个国家的名称:\n";
cout<<"第1个:";cin>>a[0];
cout<<"第2个:";cin>>a[1];
cout<<"第3个:";cin>>a[2];
cout<<"第4个:";cin>>a[3];
cout<<"第5个:";cin>>a[4];
compare te(a[0],a[1],a[2],a[3],a[4]);
te.ran();
te.print();
}

回答2:

楼主可以用strcmp来比较字符串的大小。
<0 ,当s1小于s2
strcmp(s1,s2) =0 ,当s1和s2相同
>0 ,当s1大于s2

另外,main里面要改一下
char a[5][80];
cout<<"请输入5个国家的名称:\n";
cout<<"第1个:";cin>>a[0];
cout<<"第2个:";cin>>a[1];
cout<<"第3个:";cin>>a[2];
cout<<"第4个:";cin>>a[3];
cout<<"第5个:";cin>>a[4];

就直接分配一个二维数组,每行多分配一点,万一你要输入特里尼达和多巴哥,10个字符肯定不够用。不要吝惜内存空间,才几百字节而已。

回答3:

#include
#include

class CCompare
{
public:
CCompare(char *,char *,char *,char *,char *);
int Run();
void Print();
private:
char *m_pStr[5];
};

CCompare::CCompare(char *s0, char *s1, char *s2, char *s3, char *s4)
{
m_pStr[0] = s0;
m_pStr[1] = s1;
m_pStr[2] = s2;
m_pStr[3] = s3;
m_pStr[4] = s4;
}

int CCompare::Run()
{
char *pstr = NULL;
for (int i=0; i<4; i++) //采用冒泡排序
for (int j=i; j<=4; j++)
{
if (strcmp(m_pStr[i], m_pStr[j]) > 0)
{
pstr = m_pStr[i];
m_pStr[i] = m_pStr[j];
m_pStr[j] = pstr;
}
}
return 0;
}

void CCompare::Print()
{
for(int i=0; i<5; cout<}

void main()
{
char *a[5];
a[0] = new char[10]; //动态分配空间
a[1] = new char[10];
a[2] = new char[10];
a[3] = new char[10];
a[4] = new char[10];

cout<<"请输入5个国家的名称:\n";
cout<<"第1个:";
cin>>a[0]; //输入字符串,不能用 cin>>*a[0]
cout<<"第2个:";
cin>>a[1];
cout<<"第3个:";
cin>>a[2];
cout<<"第4个:";
cin>>a[3];
cout<<"第5个:";
cin>>a[4];

CCompare te(a[0], a[1], a[2], a[3], a[4]);
te.Run();
te.Print();

delete []a[0]; //释放内存
delete []a[1];
delete []a[2];
delete []a[3];
delete []a[4];
return;
}

回答4:

#include
#include
main()
{
char a[5][10];
int i,j;
for(i=1;i<=5;i++)
scanf("%s",&a[i]);
printf("from small to big:");
for(i=1;i<=4;i++)
{
for(j=i+1;j<=5;j++)
{
if(strcmp(a[i],a[j])>0)
{strcpy(a[0],a[i]);strcpy(a[i],a[j]);strcpy(a[j],a[0]);}
}
}
for(i=1;i<=5;i++)
printf("\n%s",a[i]);
}