用c++实现编写一个函数,统计一条英文句子中字母的个数,在主程序中实现输入输出。
时间: 2024-03-14 14:45:39 浏览: 28
好的,以下是实现该功能的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int countLetters(string sentence) {
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
if (isalpha(sentence[i])) {
count++;
}
}
return count;
}
int main() {
string sentence;
cout << "请输入一条英文句子:" << endl;
getline(cin, sentence);
int count = countLetters(sentence);
cout << "该句子中字母的个数为: " << count << endl;
return 0;
}
```
该程序中,我们定义了一个`countLetters`函数,用于统计一条英文句子中字母的个数。该函数使用了一个循环,遍历整个句子,对每个字符判断是否为字母,如果是则计数器加一。
在`main`函数中,我们先用`getline`函数获取一条英文句子,然后调用`countLetters`函数统计其中字母的个数,并将结果输出。