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

C 語言字串解析數字群:Segmentation Fault 原因與修正

     編輯:程式設計綜合問答

錯誤原因

  • 死迴圈:`while(flag==1)` 迴圈內未修改 `flag`,且內層 `for` 迴圈條件 `0 <= *(str+i) && *(str+i) <= 9` 錯誤(字元比較應用 `'0'` `'9'`),導致程式卡住或越界。
  • 邏輯混亂:嘗試在單次掃描中同時完成「提取數字」與「計數」,變數交織難以維護。
  • 指標運算錯誤:`*(pstr+i-1-k)-48` 索引易出現負值越界。

簡潔正確實現

#include 
#include 

int main() {
    char s[100];
    printf("輸入字串: ");
    fgets(s, sizeof(s), stdin);

    int count = 0, inNum = 0;
    long current = 0;

    for (int i = 0; s[i]; i++) {
        if (isdigit(s[i])) {
            current = current * 10 + (s[i] - '0');
            inNum = 1;
        } else {
            if (inNum) {
                printf("%ld ", current);
                count++;
                current = 0;
                inNum = 0;
            }
        }
    }
    // 字串以數字結尾時
    if (inNum) {
        printf("%ld ", current);
        count++;
    }
    printf("\n共 %d 個數字群\n", count);
    return 0;
}

關鍵點

  1. 狀態機思想:`inNum` 標記是否正在讀數字,遇非數字輸出並重置。
  2. 使用 `isdigit` 判斷數字字元,避免 ASCII 碼硬編碼。
  3. 單次掃描、O(1) 額外空間、邏輯清晰無死迴圈。

拒絕複製貼上式修補,重寫清晰邏輯才是根治之道。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved