这是一道排序的题目。使用 C 语言编写程序,需要输入若干英文单词,将这些单词按字母表升序排序后输出。
输入格式:输入为若干英文单词,每行一个词,以 EOF 结尾。
首先,我们可以使用 fgets 函数来读入每一行的输入,直到 EOF 结尾。然后,我们可以使用字符串函数 strcmp 来比较两个字符串的大小。最后,使用冒泡排序算法对字符串数组进行排序。
示例代码:
#include <stdio.h> #include <string.h>
#define MAX_LEN 100
int main() { char words[MAX_LEN][MAX_LEN]; // 存储输入的单词 int n = 0; // 单词的个数
// 读入单词
while (fgets(words[n], MAX_LEN, stdin) != NULL)
{
n++;
}
// 冒泡排序
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (strcmp(words[j], words[j + 1]) > 0)
{
// 交换字符串
char temp[MAX_LEN];
strcpy(temp, words[j]);
strcpy(words[j], words[j + 1]);
strcpy(words[j + 1], temp);
}
}
}
// 输出排序后的单词
for (int i = 0; i < n; i++)
{
printf("%s", words[i]);
}
return 0;
}