程序統計數字、字母、其他字符,以 EOF 結束。按換行後輸入 ^Z (Windows EOF) 無輸出,必須跟在字符後才觸發。
else x[11]++,循環繼續,需再次行首輸入 Ctrl+Z 才結束。
int c = getchar(); // 返回 int,可容納 EOF(-1)
if (c == EOF) break; // 正確判斷 EOF
// 原代碼用 c == 26 判斷 Ctrl+Z,錯誤!
#include <stdio.h>
int main() {
int c; // 必須用 int 接收 getchar()
int digits[10] = {0}, letters = 0, others = 0;
while ((c = getchar()) != EOF) { // 正確 EOF 判斷
if (c >= '0' && c <= '9') digits[c - '0']++;
else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) letters++;
else others++;
}
// 輸出統計...
return 0;
}
getchar() 返回 int,**必須用 int 變量接收**,char 會截斷 EOF(-1) 變 255。26,移植性差。