美文网首页
7.5 C控制语句:简单统计单词的程序

7.5 C控制语句:简单统计单词的程序

作者: 日常表白结衣 | 来源:发表于2017-07-10 13:34 被阅读0次

统计字符数、单词数、行数
伪代码:

读取一个字符
当有更多输入时
        递增字符数
        如果读完完整一行,递增行数
        如果读完一个单词,递增单词计数
        读取下一个字符

输入实例

reason is a
powerful servant but 
an inadequate master
|

输出示例:

characters=55,words=9,lines=3,partial lines=0

程序示例:

#include<stdio.h>
#include<ctype.h>  //isspace()函数原型声明;如果参数是空白字符,isspace()=1
#include<stdbool.h>  //bool、true、false提供定义
#define STOP '|'
int main()
{
    char c; //读入字符
    char prev; //读入的前一个字符
    long n_chars = 0L;  //字符数
    int n_lines = 0, n_words = 0;
    int p_lines = 0;  //不完整的行数
    bool inword = false;  //读入单词首字符时把标志位(inword)置1
    printf("enter text to be anylzed (| to termeniante ):\n");
    prev = '\n';  //用于识别完整的行
    while ((c=getchar()) != STOP)
    {
        n_chars++;   //统计字符数
        if (c == '\n')
            n_lines++;  //统计行数
        if (!isspace(c) && !inword)
        {
            inword = true;  //开始一个新单词
            n_words++;  //统计单词数量
        }
        if (isspace(c) && inword)  //单词末尾
        {
            inword = false;
        }
        prev = c;
    }
    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;
}

相关文章

网友评论

      本文标题:7.5 C控制语句:简单统计单词的程序

      本文链接:https://www.haomeiwen.com/subject/uqiyhxtx.html