include <iostream> #include <string> #include <algorithm> using namespace std; //计算字符个数 int count() { static int count = 0; return count++; } //遍历字符串 void check(char _litter) { if(('a' <= _litter && _litter <= 'z') || ('A' <= _litter && _litter <= 'Z')) count(); } int main() { //创建字符串sentence string sentence; cout << "enter a sentence: "; //从键盘输入字符串 getline(cin, sentence); //构建string迭代器,分别sentence指向字符串的开头和结尾 string::iterator str_ite_begin = sentence.begin(); string::iterator str_ite_end = sentence.end(); //用算法for_each遍历字符串,需引入头文件algorithm for_each(str_ite_begin, str_ite_end, check); //输出字符串中字符的个数 cout << count() << endl; return 0; }