思路:
数单词, 从头到尾遍历每一行, 碰到连续的字母就开始/继续一个单词, 否则就结束一个单词. 注意两点:
1. 用 isalpha() 判断是否为字母(<cctype>)
2. 用 getline() 来读入一行带有空格的字符串
代码:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char const *argv[])
{
string str;
getline(cin, str);
while ( !cin.eof() ){
int count = 0;
bool newWorld = false;
int length = str.length();
for(int i=0; i<length; i++){
if( isalpha(str[i]) ){
if( !newWorld ){
newWorld = true;
}
}else{
if( newWorld ){
++count;
newWorld = false;
}
}
}
// 如果最后一个是字母, 则要添加对最后一个单词的统计
if( isalpha(str[length-1]) ){
++count;
}
cout << count << endl;
getline(cin, str);
}
return 0;
}
环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE