本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。

输入格式:

输入给出一行字符。

输出格式:

在一行中输出单词个数。

输入样例:

1
Let's go to room 209.

输出样例:

1
5

鸣谢用户 张麦麦 补充数据!

思路

getline输入字符串,扫描字符串

遇到字母时,若这个字母的前一个字符不是空格,则是一个新单词

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
string str;
getline(cin, str);
char ch = ' '; //当前位置的前一个字符
int ret = 0;
for(int i=0;i<(int)str.size();i++) {
char it=str[i];
if(it != ' ' && ch == ' ') {
ret++;
}
ch = it;
}
cout << ret << endl;
return 0;
}