一个统计字数的程序

本文介绍了一个C语言程序,用于统计输入文本的字符数、单词数和行数。程序通过读取字符并判断其是否为空格、换行符来计算各个指标,并在遇到特定终止符'|'时结束输入。程序使用了bool类型和isspace()函数来辅助判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面程序统计字符、单词和行

#include<stdio.h>
#include<ctype.h>             //为isspace( )提供函数原型
#include<stdbool.h>          //为bool、true和false提供定义
#define STOP '|'
int main (void)
{
    char c;
    char prev;
    long n_chars=0l;
    int n_lines=0;
    int n_words=0;
    int p_lines=0;
    bool inword=false;


    printf("Enter text to be analyzed(| to terminate):\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("pratial lines=%d\n",p_lines);
    return 0;
}

检测非空白字符最简单明了的判断表达式是这样的:

c ! = ' ' && c ! = '\n' && c ! = '\t'           //当c不是空白字符时,该表达式为真

检测空白字符最简单明了的判断表达式是这样的:

c == ' ' && c  == '\n' && c  == '\t'           //当c是空白字符时,该表达式为真

但是,使用ctype.h中的 isspace( ) 函数会更简单。如果该函数的参数是空白字符,它就返回真。因为如果c是空白字符,isspace( c)为真;如果c不是空白字符,!isspace( c)为真。

为了知道一个字符是不是在单词里,可以在读入一个单词的首字符是把一个标志(命名为 inword)设置为1。

这种方法在每个单词开始时将inword 设为1(真),而在每个单词结束时将其设为0(假)。仅在该标志从0变为1时对单词计数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值