if(c[i]='\0') 應為 if(c[i]=='\0')。單一等號導致字串提前截斷,邏輯全亂。i 重複遞增:for 迴圈自帶 i++,迴圈體內再寫 i++ 會跳過字符。for 試圖跳過非字母,但單詞分隔符是空格,非字母不代表單詞邊界(如標點、數字)。掃描字串,維護「是否在單詞內」狀態,遇到空格且前狀態為在單詞內,計數器加一。
#include <stdio.h>
#include <ctype.h> // for isspace()
int main() {
char str[1000];
int count = 0;
int in_word = 0; // 0: 不在單詞中, 1: 在單詞中
printf("請輸入一行文字:");
fgets(str, sizeof(str), stdin); // 安全替代 gets()
for (int i = 0; str[i] != '\0'; i++) {
if (isspace((unsigned char)str[i])) { // 遇到空白字符(空格、制表、換行等)
if (in_word) {
count++;
in_word = 0;
}
} else {
in_word = 1; // 非空白字符,進入/持續單詞狀態
}
}
// 處理行末無空格直接結束的情況
if (in_word) count++;
printf("單詞數量:%d\n", count);
return 0;
}
fgets 替代危險的 gets(已從 C11 標準移除)。isspace() 涵蓋所有空白字符,比單判空格更健壯。else 分支加入 isalpha() 判斷,非字母視為分隔符。拒絕硬編碼索引操作,用狀態機思維寫出健壯、可維護的字串處理代碼。