You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言counting.c开发:如何将main中字符单词行数统计逻辑封装为独立函数

代码封装实现方案

封装思路

  • C语言不支持直接返回多个值,因此采用指针传参的方式实现多个统计结果的回传:将字符、单词、行数三个统计变量的地址传入自定义函数,函数内部直接修改对应地址存储的数值即可
  • 所有读取标准输入、计数统计的逻辑全部封装到独立函数中,main函数仅负责变量声明、调用统计函数、输出结果三个步骤,符合作业要求
  • 额外优化点:将原代码中硬编码的ASCII数值替换为字符字面量,提升可读性;将存储输入的变量改为int类型,避免char为无符号类型时无法正确判断EOF的问题

完整可运行代码

#include <stdio.h>

// 自定义统计函数:从stdin读取内容直到EOF,统计字符、单词、行数
void count_stdin(unsigned long *char_cnt, unsigned long *word_cnt, unsigned long *line_cnt) {
    // 初始化统计变量与单词分隔标记
    *char_cnt = 0;
    *word_cnt = 0;
    *line_cnt = 0;
    int wrd = 1;
    // getchar返回值为int,需用int类型存储才能正确匹配EOF值
    int input;

    while ((input = getchar()) != EOF) {
        // 统计字符数
        *char_cnt += 1;
        
        // 统计行数
        if (input == '\n') {
            *line_cnt += 1;
            wrd = 1;
        }
    
        // 统计单词数:匹配大小写字母、单引号
        if ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z') || input == '\'') {
            if (wrd == 1) {
                *word_cnt += 1;
                wrd = 0;
            }
        } else {
            wrd = 1;
        }
    }
}

int main(void) {
    unsigned long charCount, wordCount, lineCount;
    // 传入三个统计变量的地址,调用自定义统计函数
    count_stdin(&charCount, &wordCount, &lineCount);
    // 输出统计结果
    printf("%lu %lu %lu\n", charCount, wordCount, lineCount);
    return 0;
}

内容的提问来源于stack exchange,提问作者Sultan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:54:03