c - 统计字符串"字母,空格,数字,其他字符"的个数和行数.

 1 #include <stdio.h>
 2 #include <ctype.h>
 3 
 4 using namespace std;
 5 
 6 /*
 7 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
 8 */
 9 
10 void
11 count() {
12     //统计个数.
13     int letters = 0; 
14     int spaces = 0; 
15     int digit = 0;
16     int others = 0;    
17     char curChar;
18     //注意的是,对(一行中)逐个字符进行读取时,'\n'对应ASCII值为10,而不是0,所以需要跟'\n'判断(不同于逐句判断).
19     while((curChar = getchar()) != '\n') {
20         if(isalpha(curChar))    //检查参数curChar是否为英文字母,在标准c中相当于使用“isupper(curChar)||islower(curChar)”
21             ++letters;
22         else if(isdigit(curChar))    //检查参数curChar是否为阿拉伯数字0到9.
23             ++digit;
24         else if(isspace(curChar))
25             ++spaces;
26         else ++others;
27     }
28 
29     printf("letters:%d, digits:%d, spaces:%d,others:%d\n", letters, digit, spaces, others);
30     //cout<<"letters:"<<letters<<",digits:"<<digit<<",spaces:"<<spaces<<",others:"<<others<<endl;
31 }
32 
33 //统计行数.
34 int
35 countLines(char *input) {
36     int lns = 0;
37     while(gets(input))
38         ++lns;
39     return lns;
40 }
41 
42 int
43 main(void) {
44     printf("enter a string:");
45     count();
46 
47     //char *t;
48     //gets(t);    
49     //Run-Time Check Failure #3 - The variable 't' is being used without being initialized.
50     /*
51     值得注意的是,如果不小心传递给gets函数的参数是为开辟空间的指针变量't',会报以上的异常.其实原因也很简单,t没有得到内存空间(即没有指向内存中的合法空间),放到gets中自然不能被使用.
52     */
53 
54     char cs[10240];
55     int lns = countLines(cs);
56     printf("lines:%d\n", lns);
57 }

 

转载于:https://www.cnblogs.com/listened/p/4134612.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值