65,208
社区成员
发帖
与我相关
我的任务
分享
#ifndef words_wy
#define words_wy
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class words
{
private:
string filename;
string word;
ifstream fin;
public:
words();
words(string &fn,string &wd);
int openfile(string &fn);
void setWord(string &wd);
int statistics();
};
#endif
#include "words.h"
#define YES 1 /* 输入的单词未完 */
#define NO 0 /* 下面是一个新单词 */
string IntToString(int & i)
{
string s;
stringstream ss(s);
ss<<i;
return ss.str();
}
words::words()
{
filename = "";
word = "";
}
words::words(string &fn,string &wd)
{
filename = fn;
word = wd;
}
int words::openfile(string &fn)
{
fin.open("TomSawyar.txt",ios::in);
return 1;
}
void words::setWord(string &wd)
{
word = wd;
}
int words::statistics()
{
int c,i=0,nl=0, nw=0, nc=0, inword= NO;//nw:单词数,nc:出现次数
int ar[20] = {0};
string strs = "";
while ((c=getchar( ))!= EOF)
{
if(c=='\n')
{
++nl;
}
if(c==' '||c=='\n'||c=='\t'||c=='.'||c==',')
{
i=0;
inword=NO;//表示准备下一个新单词
}
else
{
ar[i] = c;
i++;
for(int j=0;j<=i;j++)
{
int &temp= ar[j];
strs+=IntToString(temp);
if(strs == word)
{
cout<<"<line"<<nl<<">"<<"has the word--"<<word<<endl;
nc++;
}
}
}
if(inword==NO)
{
inword=YES;
++nw;
}
}
cout<<"The word has__"<<nc<<"__ times in the txt"<<endl;
}
#include "words.cpp"
void main()
{
string word;
cout<<"Please set the word:"<<endl;
cin>>word;
words a("TomSwayer.txt",word);
a.openfile();
a.statistics();
}