原代碼問題
for(ch=0; ch!='\n';) {
ch=getchar();
if ch='\n' break; // 語法錯誤:缺括號、賦值而非比較
// ...
}
修正代碼
#include
int main() {
int ch, letter=0, space=0, digit=0, other=0;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') letter++;
else if (ch == ' ') space++;
else if (ch >= '0' && ch <= '9') digit++;
else other++;
}
printf("字母=%d,空格=%d,數字=%d,其他=%d\n", letter, space, digit, other);
return 0;
}
關鍵修正
- 循環條件直接在 `while` 中完成讀取與判斷,無需 `if break`。
- 字符分類用標準庫 ``:`isalpha(ch)`、`isspace(ch)`、`isdigit(ch)` 更可移植。
- `ch` 定義為 `int` 接收 `EOF`。