对于给定的一个字符串,统计其中数字字符出现的次数。
Input
输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。
Output
对于每个测试实例,输出该串中数值的个数,每个输出占一行。
Sample Input
2 asdfasdf123123asdfasdf asdf111111111asdfasdfasdf
Sample Output
6 9
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
char c[1000];
getchar();
for(int i=0;i<n;i++)
{
int sum;
int length;
sum=0;
gets(c);
length=strlen(c);
for(int i=0;i<=length;i++)
{
if(c[i]<='9'&&c[i]>='0')
sum++;
}
cout<<sum<<endl;
}
return 0;
}
对于这道题,我是用的是用gets函数来接受字符串,对于样例输入,如果没有考虑到2后面的回车,则回车符之前的空字符串会被读取为一个字符串,长度为零。会对该题造成干扰,所以在输入2之后,使用个getchar()来吸收掉回车符。
但为什么在第一个字符串后面也使用一个getchar()来吸收掉回车呢?笔者这样试了一下,结果是wrong answre,经上网查询得知:gets()函数会读取一行字符,直到遇到换行符'\n为止,并且这个换行符不会读取到数组中。所以无需使用getchar(),写篇博客记录下这个问题,希望以后不会再犯