码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-12-01 12:38:11      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   使用   sp   div   log   

 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 }

 

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

标签:style   blog   io   ar   color   使用   sp   div   log   

原文地址:http://www.cnblogs.com/listened/p/4134612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!