c++编写程序输入一行字符串,统计其中英文字符、数字、空格及其他字符的个数,
时间: 2023-07-10 10:03:53 浏览: 54
可以使用C++中的字符处理函数`isalpha()`、`isdigit()`和`isspace()`来判断字符类型,然后遍历字符串进行统计。
以下是示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100];
int alphaCount = 0, digitCount = 0, spaceCount = 0, otherCount = 0;
cout << "请输入一个字符串:" << endl;
cin.getline(str, 100);
for(int i = 0; i < strlen(str); i++)
{
if(isalpha(str[i])) alphaCount++;
else if(isdigit(str[i])) digitCount++;
else if(isspace(str[i])) spaceCount++;
else otherCount++;
}
cout << "字母个数:" << alphaCount << endl;
cout << "数字个数:" << digitCount << endl;
cout << "空格个数:" << spaceCount << endl;
cout << "其他字符个数:" << otherCount << endl;
return 0;
}
```
输入示例:`Hello World! 233`
输出示例:
```
请输入一个字符串:
Hello World! 233
字母个数:10
数字个数:3
空格个数:2
其他字符个数:1
```