輸入多行英文句子,將每個單詞首字母轉為大寫輸出。
#include <stdio.h>
#include <ctype.h>
int main() {
char line[101];
while (fgets(line, sizeof(line), stdin)) {
int len = strlen(line);
if (len > 0 && line[len-1] == '\n') line[len-1] = '\0'; // 去換行
int newWord = 1; // 句首視為新單詞
for (int i = 0; line[i]; i++) {
if (newWord && islower(line[i])) {
line[i] = toupper(line[i]);
}
newWord = (line[i] == ' ');
}
printf("%s\n", line);
}
return 0;
}
fgets 逐行讀取,保留空格。newWord 標記是否處於單詞開頭(句首或空格後)。ctype.h 中 islower、toupper 處理大小寫轉換,比手動減 32 更安全可移植。輸入:
i like acm
i want to get an accepted
輸出:
I Like Acm
I Want To Get An Accepted
代碼簡潔健壯,符合題目所有要求。