輸入一行英文句子(長度 ≤ 80,單詞間單空格分隔),將單詞順序逆序輸出,單詞內部字符順序不變。
fgets 或 gets(注意安全性)#include <stdio.h>
#include <string.h>
int main(void) {
char line[81];
char words[41][81]; // 最多 40 個單詞(單字符+空格),每詞長 ≤ 80
int word_count = 0;
int len, i, j = 0;
fgets(line, sizeof(line), stdin);
len = strlen(line);
if (line[len-1] == '\n') line[--len] = '\0'; // 去除換行符
// 分割單詞
for (i = 0; i <= len; i++) {
if (line[i] == ' ' || line[i] == '\0') {
words[word_count][j] = '\0';
word_count++;
j = 0;
} else {
words[word_count][j++] = line[i];
}
}
// 逆序輸出
for (i = word_count - 1; i >= 0; i--) {
printf("%s", words[i]);
if (i > 0) printf(" ");
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char line[81];
char *words[41];
int count = 0;
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0'; // 去除換行
// strtok 分割,直接指向原字符串
char *token = strtok(line, " ");
while (token && count < 41) {
words[count++] = token;
token = strtok(NULL, " ");
}
for (int i = count - 1; i >= 0; i--) {
printf("%s%c", words[i], i ? ' ' : '\n');
}
return 0;
}
原作者發現將 words 定義為局部變量時在某些 IDE 中輸出亂碼,但提交 PAT 均通過。原因可能是:
strtok 或手動分割邏輯memset(words, 0, sizeof(words))輸入:Hello World Here I Come 輸出:Come I Here World Hello