编写一段c++代码输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
时间: 2023-04-04 08:00:56 浏览: 111
好的,这是一个关于C语言的问题。以下是代码示例:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char c;
int letter = , space = , digit = , other = ;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n') {
if (isalpha(c)) {
letter++;
} else if (isspace(c)) {
space++;
} else if (isdigit(c)) {
digit++;
} else {
other++;
}
}
printf("其中英文字母个数为:%d\n", letter);
printf("其中空格个数为:%d\n", space);
printf("其中数字个数为:%d\n", digit);
printf("其中其它字符个数为:%d\n", other);
return ;
}
```
希望能对您有所帮助。
相关问题
C++输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
C++输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数可以使用getchar()函数逐个读取字符,并根据字符的ASCII码值判断其属于哪一类。具体实现可以参考以下代码:
```
#include <iostream>
using namespace std;
int main() {
char c;
int letter = 0, space = 0, number = 0, other = 0;
cout << "请输入一行字符:" << endl;
while ((c = getchar()) && (c != '\n')) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
letter++;
else if (c == ' ')
space++;
else if (c >= '0' && c <= '9')
number++;
else
other++;
}
cout << "英文字母个数为:" << letter << endl;
cout << "空格个数为:" << space << endl;
cout << "数字个数为:" << number << endl;
cout << "其他字符个数为:" << other << endl;
return 0;
}
```
c++输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
以下是C++统计输入字符串中英文字母、数字、空格及其他字符个数的代码示例:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100];
int letter = 0, digit = 0, space = 0, other = 0;
cout << "请输入一行字符:" << endl;
cin.getline(str, 100); // 读取一行字符串
int len = strlen(str);
for (int i = 0; i < len; i++)
{
if (isalpha(str[i])) // 判断是否为字母
letter++;
else if (isdigit(str[i])) // 判断是否为数字
digit++;
else if (isspace(str[i])) // 判断是否为空格
space++;
else // 其他字符
other++;
}
cout << "字母个数:" << letter << endl;
cout << "数字个数:" << digit << endl;
cout << "空格个数:" << space << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)