C语言编程(练习5:字符串与字符串函数)

来源:互联网 发布:mobiscroll.custom.js 编辑:程序博客网 时间:2024/05/12 09:43

题目:编写一个程序。功能是读取输入,直到遇到EOF,并报告单词数、大写字母数、小写字母数、标点符号数和数字字符数。使用ctype.h系列的函数 

代码实现:

/**< 编写一个程序。功能是读取输入,直到遇到EOF,并报告单词数、大写字母数、小写字母数、标点符号数和数字字符数。使用ctype.h系列的函数 */#include <stdio.h>#include <stdlib.h>#include <ctype.h>#define MAX 100int main(){    int word = 0;    int upper = 0;    int lower = 0;    int punct = 0;    int digit = 0;    int flag = 0;   //进入单词标志位    int pflag = 0;    char str[MAX];    char *pstr = str;    printf("输入字符\n");    while((*pstr++ = getchar()) != EOF) continue;    *pstr = '\0';    for(pstr=str; *pstr!='\0'; pstr++)    {        if(isupper(*pstr)) upper++;        else if(islower(*pstr)) lower++;        else if(ispunct(*pstr)) punct++;        else if(isdigit(*pstr)) digit++;    }    for(pstr=str; *pstr!='\0'; pstr++)      //判断字符串中的单词数 用两个标志位来判断单词    {        if(isalpha(*pstr)) flag = 1;        else        {            if(pflag==1) word++;            flag = 0;        }        pflag = flag;    }    printf("word = %d\n", word);    printf("upper = %d\n", upper);    printf("lower = %d\n", lower);    printf("punct = %d\n", punct);    printf("digit = %d\n", digit);    return 0;}
运行结果:



0 0