统计单词的个数
小于 1 分钟
输入一行字符串(单词和若干空格), 输出该行单词个数。
Input:____hello_________world_ how___are___you___\n
Output: 5
#include <iostream>
using std::cout;
using std::endl;
int main() {
int word = 0;
bool flag = 0;
char content;
cout << "请输入一行字符:" << endl;
while((content = getchar()) && (content != '\n')) {
if((content >= 'a' && content <= 'z') || (content >= 'A' && content <= 'Z')) { if(flag == 0) {
++word;
flag = 1;
}
}
else if(content == ' '){
flag = 0;
}
}
cout << "个数为:" << word << endl;
return 0;
}