原题链接:[编程入门]字符串分类统计
解题思路和注意事项:
在这里我们会用到getchar()函数,简单来说,getchar()就是从键盘获取字符,直到回车为止;
代码中while里的表达式(c = getchar()) != '\n',意思是,当输入的字符不是换行符的时候,继续往下执行;
注意这里的括号不能丢,因为!=的优先级比=高,如果去掉了外面的括号就等价于 c = (getchar()!='\n');
参考代码:
#include<stdio.h>
int main()
{
int letter = 0,number = 0,blank = 0,others = 0,c; //分别为字母、数字、空格、其他
while((c = getchar()) != '\n'){
if(c >= 'A' && c<='Z' || c >= 'a' && c <= 'z') //判断是否为字母
letter++;
else if(c >= '0' && c <= '9') //判断是都为数字
number++;
else if(c == ' ') //判断是否为空格
blank++;
else //其他
others++;
}
printf("%d %d %d %d\n",letter,number,blank,others);
return 0;
}0.0分
137 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
#include<stdio.h> int main(){ int letter=0,number=0,blank=0,other=0,c; while(c!='\n'){ c = getchar(); if(c>='a' && c<='z' || c>='A' && c<='Z'){ letter++; } else if(c>='0' && c<='9'){ number++; } else if(c == ' '){ blank++; } else { other++; } } printf("%d %d %d %d\n",letter,number,blank,other-1); }为什么这个getchar()必须写到while里面?像下面这样写到外面不行? int main() { int c1=0,c2=0,c3=0,c4=0,array; array=getchar(); while(array!='\n'){ if(array>='A'&&array<='Z'||array>='a'&&array<='z') c1++; else if(array>='0'&&array<='9') c2++; else if(array==' ') c3++; else c4++; } printf("%d %d %d %d",c1,c2,c3,c4); return 0; }在c++2010都可以成功运行,为什么在这上面会出现时钟信号报错 #include<stdio.h> int main() { int E=0,shuzi=0,kongge=0,other=0; char ch; printf("请输入一字符串\n"); while((ch=getchar())!='\n') { if(ch>='A'&&ch<='Z'||ch>='a'&&ch<='z') { E++; } else if(ch>='0'&&ch<='9') { shuzi++; } else if(ch==' ') { kongge++; } else { other++; } } printf("%d %d %d %d",E,shuzi,kongge,other); return 0; }为啥我一到读入空格就出问题 #include<stdio.h> #define N 200 #include<string.h> int main() { char a[N]; int i,E=0,shuzi=0,kongge=0,other=0; scanf("%s",a); int len=strlen(a); for(i=0;i<len;i++) { if((a[i]>='A'&&a[i]<='Z')||(a[i]>='a'&&a[i]<='z')) { E++; } else if(a[i]>='0'&&a[i]<='9') { shuzi++; } else if(a[i]==' ') { kongge++; } else { other++; } } printf("%d %d %d %d",E,shuzi,kongge,other); return 0; }#include<stdio.h> int main() { int n,h=0,j=0,l=0,y=0;//h为字母数,j为数字数,l为空格数,y为其他数。 while((n = getchar()) != '\n') { if(n>='A' && n<='Z' || n>='a' && n<='z') h++; else if(n>='0' && n<='9') j++; else if(n==' ') l++; else y++; } printf("%d,%d,%d,%d",h,j,l,y); return 0; } 敢问各位大佬,我这里错在了哪里?