|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我编写的程序如下:
/***********************/
#include <stdio.h>
#include <conio.h>
void main()
{
int num[10]={0},blank=0,others=0,i;
char temp;
while((temp=getch())!='q')
{
if(temp==' ' || temp=='\t' || temp=='\n' )
{
blank++;
}
else if('0'<=temp<='9')
{
num[temp-48]+=1;
}
else
{
others++;
}
}
for(i=0;i<10;i++)
{
printf("num[%d]=%d\n",i,num[i]);
}
printf("空白符有%d个,其他字符有%d。\n",blank,others);
}
/*********************************************/
问题1:此程序无法统计字母,回车 "\n" 等其他字符,但却可以统计数字及空格和 "\t" 是怎么回事?
问题2:把while((temp=getch())!='q')此句中的'q'改为EOF,输入"ctrl" + "z"或者是"ctrl" "+" "z"都结束不了程序,这是为什么?
最大的错误在判断数字的条件那里。
EOF是一个宏定义,其值是-1
在输入过程中,按下Ctrl Z组合键,其键值并不是-1
我一般都是用getchar读取键盘输入。Ctrl Z会清空缓冲区,在没有输入任何指导情况下,按Ctrl Z,getchar就会读到-1,若有其他内容输入,则需要按两次Ctrl Z,第一次清空缓冲区,第二次会让getchar得到-1
- #include <stdio.h>
- #include <conio.h>
- void main()
- {
- int num[10]={0},blank=0,others=0,i;
- char temp;
- while((temp=getchar())!='q')
- {
- if(temp==' ' || temp=='\t' || temp=='\n' )
- {
- blank++;
- }
- else if('0'<=temp && temp<='9') //这里条件写错啦,不能连续写,需要分开
- {
- num[temp-48]+=1;
- }
- else
- {
- others++;
- }
- }
- for(i=0;i<10;i++)
- {
- printf("num[%d]=%d\n",i,num[i]);
- }
- printf("空白符有%d个,其他字符有%d。\n",blank,others);
- }
复制代码
|
|