用C++string类作为形参统计从键盘输入的字符串中字母、数字、空格和其他字符数的个数
时间: 2023-11-19 22:56:09 浏览: 57
以下是用C++的string类作为形参统计从键盘输入的字符串中字母、数字、空格和其他字符数的个数的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
void countChars(string str, int& letters, int& digits, int& spaces, int& others) {
letters = digits = spaces = others = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
if (isalpha(ch)) letters++;
else if (isdigit(ch)) digits++;
else if (isspace(ch)) spaces++;
else others++;
}
}
int main() {
string input;
cout << "Enter a string: ";
getline(cin, input);
int letters, digits, spaces, others;
countChars(input, letters, digits, spaces, others);
cout << "Letters: " << letters << endl;
cout << "Digits: " << digits << endl;
cout << "Spaces: " << spaces << endl;
cout << "Others: " << others << endl;
return 0;
}
```
在这个示例中,`countChars`函数接受一个`string`类型的参数`str`,以及四个引用类型的参数`letters`、`digits`、`spaces`、`others`,用于统计字符串中字母、数字、空格和其他字符的个数。在函数中,首先将这四个参数的值初始化为0,然后遍历字符串中的每个字符,根据字符的类型将相应的计数器加1。最后,在`main`函数中,使用`getline`函数从标准输入中读取一行字符串,并将其作为参数传递给`countChars`函数进行统计。最后,输出统计结果。