实现在txt文件中的搜索计数功能的算法,求指点!
想用一下程序实现读取DC.txt文件里的“电信”出现的个数,结果实现不了,感觉问题出现在strcmp(temp,"信息"),但是不知道怎么改,求指点……
int _tmain(int argc, _TCHAR* argv[])
{fstream pf;
char temp[sizeof("信息")];
int num=0;
pf.open("D:\\DC.txt",ios::in);
do
{
pf.read(temp,sizeof("信息"));
if(strcmp(temp,"信息") ) num++;
else continue;
}while(!pf.eof());
cout<<num<<endl;
return 0;
}
[解决办法]
用strstr.
char buff[1024];
FILE *p=fopen("D:\\DC.txt","rb");
if(p==0)
return 0;
int len=fread(buff,1,1024,p);
fclose(p);
int num=0;
char *pt=buff;
while(1)
{
pt=strstr(pt,"电信");
if(prt)
num++;
else
break;
}
return num;
[解决办法]
既然你选择了c++里面的文件操作模式,为什么不用string呢!
你用了char temp[sizeof("信息")];去定义一个字符串,你读取数据的时候"信息"已经占用了temp所有空间末尾根本没有添加一个'\0',结束符号,然后你在用strcmp函数里面可是默认遇到第一个'\0'结束符结束的
[解决办法]
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream pf;
string str;
string to="信息";
int num=0;
int n,n0=0;
pf.open("DC.txt",ios::in);
if(!pf)
{
cout<<"文件打开失败"<<endl;
return 1;
}
while(getline(pf,str,'\n'))
{
while((n=str.find(to,n0))!=string::npos)
{
num++;
n0=n+4;
}
n0=0; //查找下一行置为0
}
pf.close();
cout<<"信息出现"<<num<<"次"<<endl;
system("pause");
return 0;
}
[解决办法]
while(1)
{
pt=strstr(pt,"电信");
if(pt)
{ num++;
pt++;}
else
break;
}
???这样