您的位置:首页 > 其它

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

2014-12-01 11:22 176 查看
#include <stdio.h>
#include <ctype.h>

using namespace std;

/*
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*/

void
count() {
//统计个数.
int letters = 0;
int spaces = 0;
int digit = 0;
int others = 0;
char curChar;
//注意的是,对(一行中)逐个字符进行读取时,'\n'对应ASCII值为10,而不是0,所以需要跟'\n'判断(不同于逐句判断).
while((curChar = getchar()) != '\n') {
if(isalpha(curChar))    //检查参数curChar是否为英文字母,在标准c中相当于使用“isupper(curChar)||islower(curChar)”
++letters;
else if(isdigit(curChar))    //检查参数curChar是否为阿拉伯数字0到9.
++digit;
else if(isspace(curChar))
++spaces;
else ++others;
}

printf("letters:%d, digits:%d, spaces:%d,others:%d\n", letters, digit, spaces, others);
//cout<<"letters:"<<letters<<",digits:"<<digit<<",spaces:"<<spaces<<",others:"<<others<<endl;
}

//统计行数.
int
countLines(char *input) {
int lns = 0;
while(gets(input))
++lns;
return lns;
}

int
main(void) {
printf("enter a string:");
count();

//char *t;
//gets(t);
//Run-Time Check Failure #3 - The variable 't' is being used without being initialized.
/*
值得注意的是,如果不小心传递给gets函数的参数是为开辟空间的指针变量't',会报以上的异常.其实原因也很简单,t没有得到内存空间(即没有指向内存中的合法空间),放到gets中自然不能被使用.
*/

char cs[10240];
int lns = countLines(cs);
printf("lines:%d\n", lns);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐