原题链接:[编程入门]字符串分类统计
解题思路: 我们的想法是,定义变量分别存储数字,字母,空格和其他字符在字符串中出现的次数。当出现相应字符时,对应变量加一。 那么,我们就需要一个可以一个一个读入字符的函数,用来控制数据读入。每次计数都是一个重复的过程,那我们可以采用循环结构。
这里介绍一个函数,getchar()函数用来读入字符,当遇到回车时,结束读入过程。我们可以用while循环和此函数完成此题。具体代码如下:
注意事项:1.要注意while循环控制条件中 (c=getchar())最外层括号不可省略,具体可参考C语言运算符优先级参考表。
2.if选择结构中也可不采用ASC||码,可直接用对应字符作为判断条件
参考代码:
#include<stdio.h>
int main()
{
int num=0,letter=0,space=0,other=0;
int c;
while((c=getchar())!='\n')
{
if(48<=c&&c<=57)
num++;
else if(65<=c&&c<=90||97<=c&&c<=122)
letter++;
else if(c==32)
space++;
else other++;
}
printf("%d %d %d %d",letter,num,space,other);
return 0;
}0.0分
22 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
#include <stdio.h> int main(int argc, char const *argv[]) { int ch; int alphabets,numbers,blanks,others = 0; while((ch = getchar()) != '\n') { if(ch >= 65 && ch <= 90||ch >= 97 && ch <= 122) alphabets++; else if(ch >= 48 && ch <= 57) numbers++; else if(ch == 32 ) blanks++; else others++; } printf("%d %d %d %d", alphabets,numbers,blanks,others); return 0; } 为什么numbers的结果不对?#include<stdio.h> int main() { int letter=0, number=0, blank=0, other=0,c; while ((c=getchar()) != '\n') { if (c >= 'a' && c <= 'z' or c >= 'A' && c <= 'Z') letter++; else if (c >= '0' && c <= '9') number++; else if (c == ' ') blank++; else other++; } printf("%d %d %d %d", letter, number, blank, other); }#include<stdio.h> int main(){ char ch; int a=0,b=0,c=0,d=0; while( scanf("%c",&ch)!=EOF && ch!='\n' ){ if(ch==' '){ c++; }else if(ch>='0' &&ch<='9'){ b++; }else if( (ch>='a' && ch>='z') || (ch>='A' && ch>='Z')){ a++; }else{ d++; } } printf("%d %d %d %d\n",a,b,c,d); return 0; } 请问为啥这样就提交不过去