写一个C++程序:输人一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2024-03-22 09:17:24 浏览: 19
好的,下面是你需要的C程序:
```
#include <stdio.h>
int main() {
char str[100];
int letters=0, spaces=0, digits=0, others=0,i;
printf("请输入一行字符:\n");
fgets(str, 100, stdin); //从标准输入读取一行字符
for(i=0; str[i]!='\0'; i++)
{
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))
letters++;
else if(str[i]==' ')
spaces++;
else if(str[i]>='0'&&str[i]<='9')
digits++;
else
others++;
}
printf("输入的字符中,英文字母个数为:%d,空格个数为:%d,数字个数为:%d,其他字符个数为:%d", letters, spaces, digits, others);
return 0;
}
```
请注意,此程序只能统计ASCII码的字符,对于其他语言的字符可能无法正确处理。
相关问题
C++输人一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
可以使用字符数组来读入一行字符,然后遍历每个字符统计它们的类型。下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
char str[100];
int letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;
cout << "请输入一行字符:";
cin.getline(str, 100);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letter_count++;
} else if (isspace(str[i])) {
space_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else {
other_count++;
}
}
cout << "英文字母个数:" << letter_count << endl;
cout << "空格个数:" << space_count << endl;
cout << "数字个数:" << digit_count << endl;
cout << "其他字符个数:" << other_count << endl;
return 0;
}
```
注:`isalpha`、`isspace`、`isdigit` 是 C++ 标准库中的函数,用于判断字符的类型。
使用c++编写:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
使用C语言编写输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数的程序:#include <stdio.h>
int main()
{
char str[100];
int letter = 0, space = 0, digit = 0, other = 0;
gets(str);
int i = 0;
while(str[i] != '\0')
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
letter++;
}
else if(str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else if(str[i] == ' ')
{
space++;
}
else
{
other++;
}
i++;
}
printf("字母个数:%d\n", letter);
printf("空格个数:%d\n", space);
printf("数字个数:%d\n", digit);
printf("其它字符个数:%d\n", other);
return 0;
}