C++ txt单词检索 作业贴=。=
首先声明,这是个作业贴,实现用户输入一个字符,在规定的txt中(不需用户输入是哪个txt,代码里给定),显示该字符出现了几次即可.
在VC6.0下调试,还求高手赐教,我感觉自己问题在于构造函数写错了
就三个文件
words.h:
- C/C++ code
#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();};#endifwords.cpp:
- C/C++ code
#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;} main.cpp:
- C/C++ code
#include "words.cpp"void main(){ string word; cout<<"Please set the word:"<<endl; cin>>word; words a("TomSwayer.txt",word); a.openfile(); a.statistics();}[解决办法]
[解决办法]
我觉得楼主自己实现这个比较累啊。既然能够用到类了说明是C++的啦,那你就直接使用map来做吧,具体的参考C++ Prime里面介绍用map统计字符串的次数的
[解决办法]
不知道1楼是什么意思
string::find(目标串, int nPos=0);
用这个函数来查找,否则自己写
#include "stdafx.h"
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
int main()
{
string str="nihaohello,hello,345,hello3";
string str2="hello";
int nPos=0;
int count=0;
int i;
int len=str2.length();
while( ( i= str.find(str2 , nPos) )>0 )
{
nPos=i+ len;
count++;
}
cout<<count<<endl;
return 0;
}
[解决办法]
没看过这本书,能否贡献代码
map 也有个find,是比较key,请问 统计单词,用key合适吗??
set好像还这个好吧