題目描述
本題要求編寫程序,讀入5個字符串,按由小到大的順序輸出。
輸入格式:
輸入為由空格分隔的5個非空字符串,每個字符串不包括空格、制表符、換行符等空白字符,長度小於80。
輸出格式:
按照以下格式輸出排序后的結果:
After sorted:
每行一個字符串
輸入樣例:
red yellow blue green white
輸出樣例:
After sorted:
blue
green
red
white
yellow
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str[6];
cin >> str[0] >> str[1] >> str[2] >> str[3] >> str[4];
sort(str,str+5); //尾地址的下一個地址
cout << "After sorted:" << endl;
for(int i=0;i<5;i++)
cout << str[i] << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch[5][80];
int i,j;
for(i=0;i<5;i++)
{
scanf("%s",ch[i]);//親測gets不行
}
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(strcmp(ch[j],ch[j+1])>0)//冒泡法排序,其他法當然也可以
{
char temp[80];
strcpy(temp,ch[j]);
strcpy(ch[j],ch[j+1]);
strcpy(ch[j+1],temp);//字符串跟數字、字符不同噢
}
}
}
printf("After sorted:\n");
for(i=0;i<5;i++)
{
puts(ch[i]);
}
return 0;
}