C语言程序设计:字典序排序字符串
分析:本题需要读入多行字符串,可以使用'fgets'函数逐行读入,再使用'qsort'函数进行排序,最后输出排序后的字符串即可。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return strcmp((char *)a, (char *)b);
}
int main() {
char str[100][100];
int i = 0;
while (fgets(str[i], 100, stdin) != NULL) {
str[i][strcspn(str[i], "\n")] = 0; // 去除换行符
i++;
}
qsort(str, i, sizeof(str[0]), compare);
for (int j = 0; j < i; j++) {
printf("%s\n", str[j]);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/omcY 著作权归作者所有。请勿转载和采集!