輸入若干英文單詞,首字母轉大寫、其餘小寫,按字典序排序輸出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int cmp(const void *a, const void *b) {
return strcmp(*(char**)a, *(char**)b);
}
int main() {
int n;
printf("單詞數量: ");
scanf("%d", &n);
getchar(); // 吸收換行
char **words = malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
words[i] = malloc(100);
fgets(words[i], 100, stdin);
words[i][strcspn(words[i], "\n")] = '\0'; // 去除換行
// 首字母大寫,其餘小寫
if (words[i][0]) words[i][0] = toupper(words[i][0]);
for (int j = 1; words[i][j]; j++) words[i][j] = tolower(words[i][j]);
}
qsort(words, n, sizeof(char*), cmp);
for (int i = 0; i < n; i++) {
printf("%s\n", words[i]);
free(words[i]);
}
free(words);
return 0;
}
qsort 比較函數接收 const void*,實際為 char**,需雙重解參考 *(char**)a。toupper/tolower 需 <ctype.h>,處理非字母字元安全 (原樣返回)。malloc/free 成對使用,避免洩漏。scanf 後 getchar() 吸收換行,否則首個 fgets 讀到空行。單詞數量: 5
wORd
HellO
yEllow
she
APPLE
Apple
Hello
She
Word
Yellow