C++ 编写程序计算 sentence 中有多少个单词
发布网友
发布时间:2022-05-13 22:43
我来回答
共1个回答
热心网友
时间:2023-11-03 13:15
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string line1="We were her pride of 10 she named us:";
string line2="Benjamin, Phoenix, the Prodigal";
string line3="and perspicacious pacific Suzanne";
string sentence=line1+' '+line2+' '+line3;
string separators(" \t:,\v\r\n\f");
string word;
string::size_type maxLen,minLen,wordLen,count=0;
vector<string> longestWords,shortestWords;
string::size_type startPos=0,endPos=0;
while((startPos=sentence.find_first_not_of(separators,endPos))
!=string::npos){
//找到下个单词的起始位置
++count;
//找到下个单词的结束位置
endPos=sentence.find_first_of(separators,startPos);
if(endPos==string::npos) //如果为最后一个单词
wordLen=sentence.size()-startPos;
else
wordLen=endPos-startPos;
//}此处的}去掉,你加错了,此处不该结束while循环体的
word.assign(sentence.begin()+startPos,
sentence.begin()+startPos+wordLen);//获取单词
//设置下次查找的起始位置
startPos=sentence.find_first_not_of(separators,endPos);
if(count==1) {//找到是第一个单词
maxLen=wordLen;
minLen=wordLen;
longestWords.push_back(word);
shortestWords.push_back(word);
}
else{
if(wordLen>maxLen){
maxLen=wordLen;
longestWords.clear();
longestWords.push_back(word);
}
else if(wordLen==maxLen)
longestWords.push_back(word);
if(wordLen<minLen){
minLen=wordLen;
shortestWords.clear();
shortestWords.push_back(word);
}
else if(wordLen==minLen){
shortestWords.push_back(word);
}
}
}//此时加上},结束while
cout << "word amount: " << count << endl;
vector<string>::iterator iter;
cout << "longest word(s):" << endl;
iter=longestWords.begin();
while(iter!=longestWords.end())
cout << *iter++ << endl;
cout << "shortest word(s):" << endl;
iter=shortestWords.begin();
while(iter!=shortestWords.end())
cout << *iter++ << endl;
return 0;
}追问谢谢,我想问我的问题在哪里?
追答不是和你说了么!!我在程序里注释了。。。while循环体{}的位置错误