如何根据关键字,找到符合要求的txt文件????

nickyoo 2009-01-14 10:51:16
ifstream in;
string filename, line;
for (int i = 0; i < (int)m_FileList.size(); i++)
{
in.open(m_FileList[i].c_str(), fstream::in);
if(!in)
{
return;
}

while(getline(in, line))
{
//m_BaseList.m_strKeyWord.c_str()为要查找的关键字
//现在只能搜索一个关键字,比如"你好"
//如何才实现能够搜索多个关键字,比如"你好 我好 他好",就是类似于页面搜索的方式?????
if(strstr(line.c_str(), m_BaseList.m_strKeyWord.c_str()))
{
m_NeedFileList.push_back(m_FileList[i]);
break;
}
}

in.clear();
in.close();
}
...全文
89 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaoyisnail 2009-01-14
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 nickyoo 的回复:]
C/C++ codestringstr="你好 我好 他好";//如何将这个字符串的三个单独字符串依次放到KeyWordList中?vector<string>KeyWordList;
[/Quote]

上面给了例子了
nickyoo 2009-01-14
  • 打赏
  • 举报
回复
string str = "你好 我好 他好"; 

//如何将这个字符串的三个单独字符串依次放到KeyWordList中?
vector<string> KeyWordList;
xiaoyisnail 2009-01-14
  • 打赏
  • 举报
回复
例子:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>

using namespace std;

int main()
{
string m_FileList[] = {"in.txt","out.txt"};
vector<string> m_NeedFileList;

string key = "你好 我好 他好";
vector<string> keywords;
char* cp = strtok(const_cast<char*>(key.c_str()), " ");;
while(cp)
{
keywords.push_back(cp);//获得单个关键字
cp = strtok(NULL, " ");
}

vector<string>::iterator key_it;

ifstream in;
string filename, line;
bool flag;//是否搜索到

for (int i = 0; i < 2; i++)
{
in.open(m_FileList[i].c_str(), fstream::in);
if(!in)
{
cerr<<"error"<<endl;
exit(1);
}

flag = false;

while(getline(in, line))
{
key_it = keywords.begin();

while(key_it!=keywords.end())//循环查找每个关键字
{
if(strstr(line.c_str(), (*key_it).c_str()))
{
m_NeedFileList.push_back(m_FileList[i]);
flag = true;
break;
}
++key_it;
}
if(flag)
break;
}

in.clear();
in.close();
}

vector<string>::iterator it = m_NeedFileList.begin();
while(it!=m_NeedFileList.end()) //打印结果
{
cout<<*it<<endl;
++it;
}

return 0;
}
melody1128 2009-01-14
  • 打赏
  • 举报
回复
貌似要循环遍历的。。。
xiaoyisnail 2009-01-14
  • 打赏
  • 举报
回复
循环来查找所有的关键字啊

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧