首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C/C++ 統計字串空格數:gets 已死,fgets 當立,指針遍歷永流傳

     編輯:關於C語言

統計字串中空格數量是經典指針練習,但原代碼使用 gets 並混用 C/C++ I/O,存在緩衝區溢出、未初始化指針、編譯器警告等多重問題。本文重構為現代、安全、標準的 C 寫法,並解析核心邏輯。

原代碼問題清單

  • char *str; 未分配內存,gets(str) 寫入野指針 → **未定義行為,極易崩潰**。
  • gets **C11 已移除**,無長度限制,必導致緩衝區溢出。
  • 混用 printf/cout、iostream/stdio.h,風格混亂。
  • system("PAUSE") 平台相關,非標準。

現代 C 安全版(C99/C11)

#include <stdio.h>
#include <stdlib.h>

#define MAX_LEN 1024

int main(void) {
    char str[MAX_LEN] = {0};
    int count = 0;

    printf("Input a string: ");
    fflush(stdout); // 確保提示先顯示

    // fgets 讀整行,含換行符,安全限制長度
    if (fgets(str, sizeof(str), stdin) == NULL) {
        fprintf(stderr, "Read error\n");
        return EXIT_FAILURE;
    }

    // 可選:移除尾部換行符
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') str[len - 1] = '\0';

    // 指針遍歷統計空格
    for (const char *p = str; *p != '\0'; ++p) {
        if (*p == ' ') ++count;
    }

    printf("Your input string is: %s\n", str);
    printf("The Count of space = %d\n", count);

    return EXIT_SUCCESS;
}

核心邏輯:指針遍歷 vs 下標訪問

// 指針版(推薦,語義清晰、無索引變量、易優化)
for (const char *p = str; *p; ++p) if (*p == ' ') ++count;

// 下標版(等價)
for (size_t i = 0; str[i]; ++i) if (str[i] == ' ') ++count;

// 標準庫算法版(C++,C 需手寫)
// count = std::count(str, str + strlen(str), ' ');

進階:統計所有空白字符

若需統計空格、Tab、換行等所有 isspace 字符:

#include <ctype.h>
// ...
for (const char *p = str; *p; ++p) if (isspace((unsigned char)*p)) ++count;

注意:isspace 參數需轉 unsigned char 避免負值未定義行為。

編譯與運行

gcc -std=c11 -Wall -Wextra -O2 space_count.c -o space_count
./space_count

總結

  • 棄用 gets,改用 fgets + 固定緩衝區或動態分配。
  • 初始化所有指針/緩衝區,消除野指針風險。
  • 純 C 或純 C++,避免混用 I/O 庫。
  • 指針遍歷 for (const char *p = s; *p; ++p) 是 C 風格字串處理的標準慣用法,簡潔高效。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved