从键盘上输入5个字符串(约定:每个字符串中字符数≤80字节),对其进行升序排序并输出。编程可用素材:printf("Input 5 strings:\n")、printf("---------------------------\n")。
时间: 2024-05-15 18:11:52 浏览: 22
您可以使用C语言中的标准库函数qsort()来对字符串进行排序,排序前需要将字符串存储到数组中。代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 80
int cmp(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
int main() {
printf("Input 5 strings:\n");
printf("---------------------------\n");
char *strs;
char buffer[MAX_LEN];
for (int i = 0; i < 5; i++) {
fgets(buffer, MAX_LEN, stdin);
int len = strlen(buffer);
if (buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
strs[i] = malloc(len);
strcpy(strs[i], buffer);
}
qsort(strs, 5, sizeof(char *), cmp);
printf("---------------------------\n");
printf("Sorted strings:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", strs[i]);
free(strs[i]);
}
return 0;
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)