#include<bits/stdc++.h>
using namespace std;
int main()
{
string line;
getline(cin,line);
if (line.empty())
{
cout <<"0"<< endl;
return 0;
}
if (line.back()!=' ')
{
line+=' ';
}
int count=0;
for (int pos=0;pos<line.length();++pos)
{
if(line[pos]==' ')
{
count++;
}
}
cout<<count;
return 0;
}
做法二:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string st1,st2;
getline(cin,st1);
stringstream s(st1);
int ans = 0;
while(s >> st2)
{
ans++;
}
cout<<ans;
return 0;
}
使用stringstream,使代码更简洁,逻辑更清晰
题目:
英语王老师正在开发一个英语作文线上系统,需要自动计算文中的单词个数。在最初的版本中,王老师并不打算加入拼写错误检查。因此,连续的英文字母都被认为是一个“单词”,单词之间使用空格或标点符号区分。请你设计一个程序,统计一行英文输入中的单词个数。为了简便算法,已提前去除了文本中的标点符号。因此,输入的文本中只包含单词和空格。
输入格式:
输入一行带有空格的字符(不超过 1000 个字符),以换行符结尾。保证输入的字符中仅包含英文字母(包含大写字母和小写字母)和空格。
输出格式:
输出这行英文字符中单词的个数。
输入样例1:
I love Ningbo
输出样例1:
3
输入样例2:
All C programs do the same thing look at a character and do nothing with it
输出样例2:
16