首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言統計字符類型:去除多餘 break、修正條件判斷邏輯

     編輯:程式設計綜合問答

原代碼問題


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;
}

關鍵修正

  1. 循環條件直接在 `while` 中完成讀取與判斷,無需 `if break`。
  2. 字符分類用標準庫 ``:`isalpha(ch)`、`isspace(ch)`、`isdigit(ch)` 更可移植。
  3. `ch` 定義為 `int` 接收 `EOF`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved