这题我也必须写一篇博客纪念自己耗了这么长时间…
本来我想着c语言编程题目集用c++还不是随便写么,这又是一道简单的模拟题嘛!
#include <iostream>
using namespace std;
int main()
{
int cnt=0;
string s;
while(1){
cin>>s;
int l=s.length();
if(cnt++) cout<<' ';
if(s[l-1]=='.'){
if(l>1) cout<<l-1;//如果不是空句子
break;
}
else cout<<l;
}
}
然后最后一个测试点格式错误
问了老师才知道:他说以 . 结束但没说是几个 .
比如:
It’s great to see you here… (多个.)
It’s great to see you here … (多个.且与前面单词有空格)
这时候cin的弊端就出来了… (想用cin偷个懒太难了呜…)
最后一个测试点应该是第二种情况
但其实第一种也过不了(我太菜了.jpg)
考虑两种情况后:
#include <iostream>
using namespace std;
int main(){
int cnt=0;
string s;
while(1){
cin>>s;
if(s[0]=='.') break;//第二种情况
int l=s.length();
if(cnt++) cout<<' ';
if(s[l-1]=='.'){
while(s[l-1]=='.') l--;//第一种情况以及空句子
if(l) cout<<l;
break;
}
else cout<<l;
}
}
优化后:
#include <iostream>
using namespace std;
int main(){
int cnt=0;
string s;
while(cin>>s){
if(s[0]=='.') break;//.与单词不相连的情况,这里也可以用continue,但是会多进行一次cin操作
int l=s.length();
while(s[l-1]=='.') l--;//.与单词相连,减去所有.的个数后输出余下长度
if(cnt++) cout<<' ';
cout<<l;
}
}