原题链接:[编程入门]字符串分类统计
解题思路和注意事项:
在这里我们会用到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、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
@lp #include<stdio.h> void main() { int ch; int sum=0,num=0,mum=0,lum=0; while(1) { ch=getchar(); if(ch=='\n')break; if(ch>='a'&&ch<'z'||ch>='A'&&ch<='Z')sum++; if(ch>='0'&&ch<='9')num++; if(ch==' ')mum++; else lum++; } printf("%d %d %d %d",sum,num,mum,lum); }#include <stdio.h> int main () { int a=0; int b=0; int c=0; int d=0; char e; while((e=getchar())!='\n') { if(e>='a'&&c<='z'||e>='A'&&c<='Z') a++; else if(e>='0'&&e<='9') b++; else if(e==' ') c++; else d++; } printf("%d %d %d %d",a,b,c,d); return 0; } 编译器能运行 提交就错 求教#include<stdio.h> #include<ctype.h> int main(void) { int i_letter=0; int i_number=0; int i_space=0; int i_other=0; int c; printf("Please enter a string:"); while((c=getchar())!='\n') { if(isalpha(c)) i_letter++; else if(isdigit(c)) i_number++; else if(isblank(c)) i_space++; else i_other++; } printf("%d %d %d %d\n",i_letter,i_number,i_space,i_other); return 0; }