用C++中的string类作为形参统计从键盘输入的字符串中字母、数字、空格和其他字符数的个数
时间: 2023-11-19 10:12:20 浏览: 73
```c
#include <stdio.h>
#include <string.h>
void count(char str[]) {
int len = strlen(str);
int letters = 0, digits = 0, spaces = 0, others = 0;
for(int i = 0; i < len; i++) {
if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
letters++;
} else if(str[i] >= '0' && str[i] <= '9') {
digits++;
} else if(str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Others: %d\n", others);
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
count(str);
return 0;
}
```
阅读全文