用C语言输入10个国家的名称,将其按字母顺序输出
时间: 2025-06-22 09:47:03 浏览: 10
在C语言中,你可以使用数组存储这10个国家的名称,并通过字符数组排序函数如qsort来进行排序。首先,你需要创建一个动态分配内存的字符指针数组,然后接收用户输入并填充这个数组,最后对数组进行排序并打印出来。以下是简单的步骤:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义结构体存储国家名
typedef struct {
char *name;
} Country;
// 比较函数用于字符串排序
int compare(const void *a, const void *b) {
return strcmp(*(Country **)a, *(Country **)b);
}
int main() {
Country countries[10];
int i = 0;
// 输入10个国家的名称
printf("请输入10个国家的名称(每输入一个回车结束):\n");
for (i = 0; i < 10; ++i) {
char input[50];
fgets(input, sizeof(input), stdin); // 去掉换行符
countries[i].name = malloc(strlen(input) + 1);
strcpy(countries[i].name, input);
// 移除最后一个'\n'
if (countries[i].name[strlen(countries[i].name) - 1] == '\n')
countries[i].name[strlen(countries[i].name) - 1] = '\0';
}
// 对国家名数组进行排序
qsort(countries, 10, sizeof(Country), compare);
// 输出排序后的国家名
for (i = 0; i < 10; ++i) {
printf("%s\n", countries[i].name);
}
// 释放内存
for (i = 0; i < 10; ++i)
free(countries[i].name);
return 0;
}
阅读全文
相关推荐
















