c++c++(2)再编写一个子函数实现月份按字符串顺序排列,并将排序结果进行输出,其程序结构如下: #include <iostream> using namespace std; void DispMonths(char p[][30]) { … //打印12个月份 } void SortStrings(char p[][30], int n) { … } int main() { //months的定义及用字符串初始化的过程 char months[12][30]={"January","February",…}; cout<<"排序前:"<<endl; DispMonths(months); SortStrings(months,12); cout<<endl<<"排序后:"<<endl; DispMonths(months); return 0; }
时间: 2024-01-09 14:04:30 浏览: 74
c++必背单词.pdf
以下是实现月份按字符串顺序排列的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void DispMonths(char p[][30]) {
for(int i=0; i<12; i++) {
cout << p[i] << endl;
}
}
void SortStrings(char p[][30], int n) {
char temp[30];
for(int i=0; i<n-1; i++) {
for(int j=i+1; j<n; j++) {
if(strcmp(p[i], p[j]) > 0) {
strcpy(temp, p[i]);
strcpy(p[i], p[j]);
strcpy(p[j], temp);
}
}
}
}
int main() {
char months[12][30] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
cout << "排序前:" << endl;
DispMonths(months);
SortStrings(months, 12);
cout << "排序后:" << endl;
DispMonths(months);
return 0;
}
```
程序中,我们使用了C++标准库中的`strcmp()`函数来比较月份字符串大小,并且使用了`strcpy()`函数来交换两个月份字符串的位置。最终的输出结果如下:
```
排序前:
January
February
March
April
May
June
July
August
September
October
November
December
排序后:
April
August
December
February
January
July
June
March
May
November
October
September
```
阅读全文