不知道哪里出了问题
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
#include <stdio.h>
int main()
{
char a[1000];
int count=0,count1=0,count2=0,other=0;
while(scanf("%s",&a[1000])!=EOF)
{
for(int i=0;i<1000;i++)
{
if((a[i]>='a' && a[i]<='z')||(a[i]>='A' && a[i]<='Z'))
count++;
else
if(a[i]==' ')
count1++;
else
if(a[i]>='0' && a[i]<='9')
count2++;
else
other++;
}
}
printf("%d\n%d\n%d\n%d\n",count,count1,count2,other);
return 0;
}
scanf不接收空格,要用getchar
int main()
{
char a[1000] = {0}, ch;
int count = 0, count1 = 0, count2 = 0, other = 0, len = 0;
// while (scanf("%s", &a[1000]) != EOF)
while ((ch = getchar()) != '\n' && len < 1000)
{
a[len++] = ch;
}
for (int i = 0; i < len; i++)//
{
if ((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z'))
count++;
else if (a[i] == ' ')
count1++;
else if (a[i] >= '0' && a[i] <= '9')
count2++;
else
other++;
}
printf("%d\n%d\n%d\n%d\n", count, count1, count2, other);
return 0;
}
获取一行字符到字符数组, 以及遍历字符数组获取到的字符那里修改一下应该就可以了。修改如下:
#include <stdio.h>
int main()
{
char a[1000];
int count=0,count1=0,count2=0,other=0;
char ch;
int i=0;
//获取一行输入到字符数组
while((ch=getchar())!='\n'){
a[i]=ch;
i++;
}
a[i]='\0';
printf("a=%s\n",a);
//分别统计空格,英文字母,数字和其他字符的个数
i=0;
while(a[i]!='\0')
{
if((a[i]>='a' && a[i]<='z')||(a[i]>='A' && a[i]<='Z'))
count++;
else
if(a[i]==' ')
count1++;
else
if(a[i]>='0' && a[i]<='9')
count2++;
else
other++;
i++;
}
printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n",count,count1,count2,other);
return 0;
}
供参考,修改见注释:
#include <stdio.h>
int main()
{
char a[1000];
int count = 0, count1 = 0, count2 = 0, other = 0;
gets(a); //while (scanf("%s", &a[1000]) != EOF) scanf()函数遇到空格等字符即认为输入结束
//{
for (int i = 0; a[i] != '\0'; i++) //for (int i = 0; i < 1000; i++)
{
if ((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z'))
count++;
else
if (a[i] == ' ')
count1++;
else
if (a[i] >= '0' && a[i] <= '9')
count2++;
else
other++;
}
//}
printf("%d\n%d\n%d\n%d\n", count, count1, count2, other);
return 0;
}
for(int i=0;i<1000;i++)
这里i<1000是错误的,实际输入的字符串长度没有1000啊
#include <stdio.h>
int main()
{
char a[1000];
int count=0,count1=0,count2=0,other=0;
while(scanf("%s",&a[1000])!=EOF)
{
int i=0;
while(a[i] != '\0')
{
if((a[i]>='a' && a[i]<='z')||(a[i]>='A' && a[i]<='Z'))
count++;
else if(a[i]==' ')
count1++;
else if(a[i]>='0' && a[i]<='9')
count2++;
else
other++;
i++;
}
}
printf("%d\n%d\n%d\n%d\n",count,count1,count2,other);
return 0;
}
a数组没初始化