![](/img/trans.png)
[英]C++ , read line by line and search a keyword that links to a line in a file
[英]Search words in line of an external file in c++
我有以下问题:我有一个文本文件file.txt
,其中包含几行要在其中搜索特定单词的行。 我要搜索的单词在第二个文件input.txt
,该文件可能看起来像这样:
Paul
Matt
Joseph
在第一个循环中,我想搜索Paul,在第二个循环中搜索Matt,在第三个循环中搜索Joseph。 每次我在文本文件的一行中找到特定名称时,我都希望输出该行并继续搜索文本文件的所有后续行。
目前,我的代码如下所示:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream fs("input.txt");
ifstream stream1("file.txt");
ofstream stream2("output.txt");
string Name;
string line;
while (fs >> Name)
{
while (std::getline(stream1, line))
{
if ((line.find(Name) != string::npos))
{
stream2 << Name << line << endl;
}
else
stream2 << "Unable to find name in line" << endl;;
}
}
fs.close();
stream1.close();
stream2.close();
return EXIT_SUCCESS;
}
我的代码的问题在于,它搜索的第一个单词很好,但在第first loop
之后停止。 它不搜索第二个单词("eg Matt").
也许有人知道我犯了一个错误。
非常感谢 :-)
内循环完成后,您将进入stream1
文件的stream1
。 您需要将读取位置“倒回”到开头。 这可以通过寻找第一个位置来完成。
当您open
input.txt
时,如果name = Paul
则从该文件中读取所有元素。 读取全部后, cursor
将位于文件input.txt
的末尾。 这就是为什么当您再次搜索Matt时,您找不到任何东西。
因此,您应该始终从input.txt
开始搜索。 因此,您可以打开该文件,然后将光标置于第一位。
只是简单的更改:
while (fs >> Name)
{
ifstream stream1("file.txt");
while (std::getline(stream1, line))
{
if ((line.find(Name) != string::npos))
{
stream2 << Name << line << endl;
}
else
stream2 << "Unable to find name in line" << endl;;
}
stream1.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.