struct apple{
string s;
int time;
};
OK了
下面定义一个vector<apple> 就好了
真是惭愧啊 比较的时候 还是有点不清楚怎么弄...
比如文章是today is so so cool.就句话...输入的单词是so,统计它在这句话中的次数, 但是一个句号为单位的比较怎么弄呢 ...下面的比较思路对吗
... ...
#include<string>
#include<iostream>
using namespace std;
void main()
{
string sentence="today is so so cool.";
string word;
int i,j;
int times=0;
while(cin>>word)
{
for(i=0;i<sizeof(word);)
for(j=0;sentence[j]!='.';)
{
if(word[i]!=sentence[j])
{
j++;
i=0;
}
if((word[i]==word[sizeof(word)-1])&&(word[i]==sentence[j]))
{
times++;
i=0;
j++;
}
else
{
i++;
j++;
}
}
}
cout<<times<<endl;
}
... ...
只知道vector容器类 就是代替数组的 但和string联系起来 还是不会应用
就知道 vector<string>word(10); 和char word[10]是一样的 但没有体会到"容器"的真正含义....晕了... 请指教新的思路哦 ...
[此贴子已经被作者于2006-3-27 12:14:19编辑过]
#include<iostream>
#include<string>
#include<vector>
using namespace std;
inline compare(const string& s1, const string& s2)
{ return s1 == s2; }
int main()
{
vector<string> words;
vector<int> times;// times 包含了该单词出现的次数
cout << "Please enter some words"
" ctrl + z.";
cout << endl;
string s;
while(cin >> s)
{
vector<string>::size_type i = 0;
while(i != words.size())
{
if(compare(s, words[i]))
++times[i];
else
{
words.push_back(s);
times[i] = 1;
}
++i;
}
if(words.size() == 0)
{
words.push_back(s);
times[i] = 1;
}
}
vector<string>::size_type iter = 0;
//不变式:目前为止已输出了 iter 个单词 当然还有它出现的次数
while(iter != words.size())
{
cout << "Word " << words[iter] << ' '
<< times[iter] << " time(s). ";
cout << endl;
++iter;
}
cout << endl;
return 0;
}
看看
我现在是一个java程序员,好久没写c++了,感觉还真是有一些基本的东西都忘了。
#include <iostream>
#include <string>
#include <fstream>
using namespace std ;
int _tmain(int argc, _TCHAR* argv[])
{
char filePath[50];
string Word;
cout<<"Please input the file path:"<<endl;
cin>>filePath;
ifstream file;
file.open(filePath); //本来想把变量filepath也设成string,可file.open()要求char* 作为参数,而我又忘了怎么转了
if(!file)
{
cout<<"Can not open the file \""<<filePath<<"\""<<endl;
exit(EXIT_FAILURE);
}
cout<<"Which word are you looking for:"<<endl;
cin>>Word;
cout<<endl;
char c;
string word="",Sentence="";
bool OutputSentence=false;
int numWord=0;
int numOutputSentence=0;
while(file.get(c))
{
if((c>='A'&&c<='z')||(c>='a'&&c<='z'))
{
word=word+c;
}
if(c=='.'||c=='!'||c=='?'||c==' ') //可填入其它标点
{
if(word==Word)
{
OutputSentence=true;
numWord++;
}
if(word!=""||c!=' ') //消除连续的空格和句首为空格两种情况
Sentence=Sentence+word+c;
word="";
if(c=='.'||c=='!'||c=='?')
{
if(OutputSentence)
{
cout<<Sentence<<endl;
numOutputSentence++;
}
OutputSentence=false;
Sentence="";
}
}
}
cout<<endl;
if(numWord==0)
{
cout<<"There is no \""<<Word<<"\" in the file \""<< filePath<<"\"."<<endl;
}else{
cout<<"There are "<<numWord<<" \""<<Word<<"\" "<<"in "<<numOutputSentence<<" sentences."<<endl;
}
//最后一个输入语句没用,只是为了调试方便
cin>>word;
return 0;
}
[此贴子已经被作者于2006-3-28 8:32:05编辑过]