• C Primer Plus(6) 中文版 第7章 C控制语句:分支和跳转 7.4 一个统计单词的程序


    7.4 一个统计单词的程序
    判断非空白字符最直接的测试表达式是:
    c != ' ' && c != '\n' && c != '\t' 
    检测空白字符最直接的测试表达式是:
    c == ' ' || c == '\n' || c == '\t'
    使用ctype.h头文件中的函数isspace()更简单。如果该函数的参数是空白字符,则返回真。所以,如果c是空白字符,isspace(c)是真;
    如果c不是空白字符,!isspace(c)为真。
    如果使用布尔类型的变量,通常习惯把变量本身作为测试条件。如下所示:
    这里inword的值不是1就是0。 
    用if( inword )代替if( inword == true )
    用if( !inword )代替if( inword == false )
    可以这样做的原因是,如果inword为true,则表达式inword == true为true;如果inword为false,则表达式inword == true为false。
    所以,还不如直接用inword作为测试条件。类似地,!inword的值与表达式inword == false的值相同(非真即false,非假即true)。
    // wordcnt.c -- counts characters, words, lines
    #include
    #include         // for isspace()
    #include       // for bool, true, false
    #define STOP '|'
    int main(void)
    {
        char c;                 // read in character
        char prev;              // previous character read
        long n_chars = 0L;      // number of characters
        int n_lines = 0;        // number of lines
        int n_words = 0;        // number of words
        int p_lines = 0;        // number of partial lines
        bool inword = false;    // == true if c is in a word
        
        printf("Enter text to be analyzed (| to terminate):\n");
        prev = '\n';            // used to identify complete lines
        while ((c = getchar()) != STOP)
        {
            n_chars++;          // count characters
            if (c == '\n')
                n_lines++;      // count lines
            if (!isspace(c) && !inword)
            {
                inword = true;  // starting a new word
                n_words++;      // count word
            }
            if (isspace(c) && inword)
                inword = false; // reached end of word
            prev = c;           // save character value
        }
        
        if (prev != '\n')
            p_lines = 1;
        printf("characters = %ld, words = %d, lines = %d, ",
               n_chars, n_words, n_lines);
        printf("partial lines = %d\n", p_lines);
        
        return 0;
    }
    /* 输出:

    */ 

    如果c不是空白字符,且inword为假
    翻译成如下C代码:
    if( !isspace( c ) && !inword )
    上面的整个测试条件比单独判断每个空白字符的可读性高:
    if( c != ' ' && c != '\n' && c != '\t' && !inword ) 
    把ch的char类型改为int类型,while循环的中表达式STOP改为EOF就可以统计文件中的单词数量了。

  • 相关阅读:
    这篇文章带你了解:如何一次性将Centos中Mysql的数据快速导出!!!
    服务注册中心
    9 开源鸿蒙OpenHarmony上电的第一行代码,boot代码简述
    踩坑日记 uniapp Vue3 setup 语法糖 vuex 的配置 其他人写的都是垃圾 看了两小时的 csdn 最后自己终于试出来了
    pandas使用fillna函数填充dataframe中所有数据列的缺失值、使用中位数(median)填充dataframe所有数据列中的缺失值
    详解Java中String类的不可变性与底层原理
    NumPy学习挑战第四关-NumPy数组属性
    Debezium系列之:深入理解Kafka的消息代理
    windows10安装redis服务【成功安装】
    【计算机网络】网络模型
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126210782