用c语言和c++分别编写一遍输入n个字符串 (n<=10,每个字符串长度均小于20),按照从小到大的顺序输出这些字符串。
时间: 2025-01-19 13:06:39 浏览: 43
好的,我很乐意为您分别用C语言和C++编写一个程序,用于输入n个字符串并按字典序从小到大排序输出。以下是两种语言的实现:
C语言版本:
```c
#include <stdio.h>
#include <string.h>
#define MAX_N 10
#define MAX_LEN 20
int main() {
int n;
char str[MAX_N][MAX_LEN + 1];
printf("请输入字符串的数量 (1-10): ");
scanf("%d", &n);
if (n < 1 || n > MAX_N) {
printf("数量超出范围!\n");
return 1;
}
printf("请输入 %d 个字符串:\n", n);
for (int i = 0; i < n; i++) {
scanf("%s", str[i]);
}
// 使用冒泡排序进行排序
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
char temp[MAX_LEN + 1];
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
printf("排序后的字符串:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
```
C++语言版本:
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
int n;
std::vector<std::string> strings;
std::cout << "请输入字符串的数量 (1-10): ";
std::cin >> n;
if (n < 1 || n > 10) {
std::cout << "数量超出范围!" << std::endl;
return 1;
}
std::cout << "请输入 " << n << " 个字符串:" << std::endl;
for (int i = 0; i < n; i++) {
std::string s;
std::cin >> s;
strings.push_back(s);
}
// 使用std::sort进行排序
std::sort(strings.begin(), strings.end());
std::cout << "排序后的字符串:" << std::endl;
for (const auto& s : strings) {
std::cout << s << std::endl;
}
return 0;
}
```
这两个程序都实现了输入n个字符串并按字典序从小到大排序输出的功能。C语言版本使用了二维字符数组来存储字符串,而C++版本使用了vector<string>容器。C++版本利用了STL中的sort函数,使得排序过程更加简洁。
阅读全文
相关推荐















