输入一组单词,并以字典排序,以##表示输入完毕,并输出。
西大信管c++期中必考考试题
方法一
利用二维数组
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
char sorted(int n,char *words); //冒泡排序
main()
{
cout << "Enter a list of words ,input will be terminated by a line consisting of '##'"
<< endl;
char words[100][46]; //最长的一个单词45个字母
int i;
for(i=0;i<100;i++)
{
cin >> words[i];
if (words[i][1] == '#' && words[i][0] == '#')
break;
}
int n = i-1;
cout <<endl << endl
<< "There are " << n+1 << " words you have input." << endl <<endl;
cout << "The original sequence is " <<endl << endl;
for (i=0;i<n+1;i++)
cout << words[i] << endl ;
cout << endl;
sorted(n,*words);
}
char sorted(int n,char *words) //冒泡排序
{
char exwords[n][46];
int j,k,nm,fuck;
char flag[46];
for(j=0;j<n+1;j++)
for(k=0;k<46;k++)
exwords[j][k] = *(words+46*j+k);
for(j=0;j<n-1;j++)
for(k=0;k<n-1-j;k++)
{
for(nm=0;nm<46;nm++)
{
if(exwords[k][nm]<exwords[k+1][nm])
break;
if(exwords[k][nm]==exwords[k+1][nm])
continue;
if(exwords[k][nm]>exwords[k+1][nm])
{
for(fuck=0;fuck<46;fuck++)
{
flag[fuck] = exwords[k][fuck];
exwords[k][fuck] = exwords[k+1][fuck];
exwords[k+1][fuck] = flag[fuck];
}
break;
}
}
}
cout << "The current sequence is " <<endl;
for(j=0;j<n+1;j++)
cout << exwords[j] <<endl;
}
方法二
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
main()
{
cout << "Enter a list of words ,input will be terminated by a line consisting of '##'";
cout << endl;
string words[100];
words[0]="hello";
int i;
char word[100][45];
for(i=1;words[i-1]!="##";i++)
{
cin >> words[i];
}
cout << "There are " << i-2 << " words" << endl;
int n;
n = i;
sort(words+1,words+i-1);
for(i=1;i<n-1;i++)
cout << words[i] <<endl;
}
方法三
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<iterator>
using namespace std;
main()
{
cout << "Enter words: Enter \"##\" when finished" << endl;
vector<string>words;
string word;
while(getline(cin,word)&&word!="##")
words.push_back(word);
int len = words.size();
sort(words.begin(),words.end());
if(words.empty())
cout << "No words!";
else
for(int i = 0;i < len;i++)
cout << words[i] << endl;
}
来源:CSDN
作者:觌氅
链接:https://blog.csdn.net/weixin_44679926/article/details/100990980