用c++给五个单词按字母顺序排序
时间: 2024-05-10 12:19:11 浏览: 3
以下是一个简单的C++程序,可以将五个单词按字母顺序排序:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string words[5] = {"hello", "world", "apple", "banana", "cherry"};
sort(words, words+5); // 使用STL的sort函数进行排序
for(int i=0; i<5; i++)
{
cout << words[i] << endl;
}
return 0;
}
```
输出结果为:
```
apple
banana
cherry
hello
world
```
相关问题
c++编写程序,输入10个单词(每个单词小于32字符),将这些单词按升序字母顺序排序输出。
#include <stdio.h>
#include <string.h>
#define MAX_LEN 32 // 单词的最大长度
#define NUM_WORDS 10 // 单词的数量
// 字符串比较函数,用于qsort排序
int cmp(const void *a, const void *b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
char words[NUM_WORDS][MAX_LEN]; // 存储输入的单词
char *ptrs[NUM_WORDS]; // 存储单词指针,用于qsort排序
int i;
// 输入10个单词
printf("请输入10个单词(每个单词小于32字符):\n");
for (i = 0; i < NUM_WORDS; i++) {
scanf("%s", words[i]);
ptrs[i] = words[i]; // 将指针指向单词
}
// 排序
qsort(ptrs, NUM_WORDS, sizeof(char*), cmp);
// 输出排序后的单词
printf("排序后的单词:\n");
for (i = 0; i < NUM_WORDS; i++) {
printf("%s\n", ptrs[i]);
}
return 0;
}
3、编程实现:从屏幕上输入三个单词存入到字符数组中,按单词的字母顺序排序存放并输出。
以下是C++语言实现的代码:
```cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main() {
const int maxn = 100;
char words[3][maxn];
// 输入三个单词
for (int i = 0; i < 3; i++) {
cin >> words[i];
}
// 按字典序排序
sort(words, words+3);
// 输出排序后的单词
for (int i = 0; i < 3; i++) {
cout << words[i] << " ";
}
cout << endl;
return 0;
}
```
首先定义了一个字符数组 `words`,用来存放三个单词。接着使用循环输入三个单词,然后调用 `sort` 函数按照字典序对单词进行排序,最后再循环输出排序后的单词即可。