C语言经典算法100例-017-统计输入的字符数

来源:互联网 发布:java base64转换为pdf 编辑:程序博客网 时间:2024/04/30 22:33

题目如下:

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

1.分析:字符和整型可以隐式互转,字符即整数。

输出结束的标示符为‘\n’。

2.来看源程序:

#include <stdio.h>#include <conio.h>int main(){    int letters=0,spaces=0,numbers=0,others=0;    char c;    printf("Please input some characters!\n");    while((c=getchar())!='\n')    {        if(c>='a'&&c<='z'||c>='A'&&c<='Z')            letters++;        else if(c>='0'&&c<='9')            numbers++;        else if(c==' ')            spaces++;        else            others++;    }    printf("Including %d letters, %d spaces, %d numbers, and %d others!\n",letters,spaces,numbers,others);    getch();    return 0;}
这里是我首次使用conio.h,这个头文件是console i/o控制台输入输出的意思,常用函数如下:

getch():在windows平台下从控制台无回显地取一个字符,在linux下是有回显的。

getchar():读取一个字符并返回。

注意:当输入回车时getchar()得到'\n'。

   &&优先级高于||。可以先与后非无需括号。

0 0
原创粉丝点击