问题描述
逐行检查文本文件中的单词,找到时打印整行包含单词.Pleas尽快帮助。
我尝试过:
这里是代码: -
这里cw是一个指针存储在其中的行,w是要搜索的单词,gw也是用于存储从每行获得的单词的指针。
while(!o。 eof())
{
o.getline(cw,'\ n');
for(i = 0; cw [ i]!='\''; i ++)
{
gw [i] = cw [i];
}
// if(cw [i] == w [i])
if(gw == w)
cout<< cw;
如果(o.eof())休息;
}
o.close();
To check for a word in a text file line by line and when found print the whole line which is containing the word .Pleas help as fast as possible.
What I have tried:
here is the code:-
Here cw is a pointer having the line stored in it,w is the word to be searched for, gw is also a pointer used to store the word obtained from each line.
while (!o.eof())
{
o.getline(cw,'\n');
for(i=0;cw[i]!='\0';i++)
{
gw[i]=cw[i];
}
// if(cw[i]==w[i])
if(gw==w)
cout<<cw;
if(o.eof())break;
}
o.close();
推荐答案
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("in.txt");
string word = "foo";
string line;
while( getline(ifs, line ))
{
size_t pos = line.find(word);
if ( pos != string::npos)
cout << line << endl;
}
}
[update]
如果你不想要foofighters ,那就是你需要在单词边界之间搜索你的单词(如你自己和 KarstenK 所暗示的那样),那么你可以使用常规表达式:
[update]
If you don't want foofighters, that is if you need to search your word between word-boundaries (as hinted by yourself and KarstenK) then you might use a regular expression:
#include <iostream>
#include <fstream>
#include <regex>
using namespace std;
int main ()
{
ifstream ifs("in.txt");
string word = "foo";
std::regex e{"\\b" + word + "\\b"};
string line;
while( getline(ifs, line ))
{
if ( regex_search( line, e) )
cout << line << endl;
}
}
[/ update]
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::cout << "Write the path of the file\n";
std::string path;
std::cin >> path;
std::ifstream file(path.c_str());
if (file.is_open())
{
std::cout << "File '" << path << "' opened.\n";
std::cout << "Write the word you're searching for\n";
std::string word;
std::cin >> word;
std::string line;
std::string candidate;
while (!file.eof()) // for each candidate word read from the file
{
std::getline(file, line);
std::size_t found = line.find(word);
if (found != std::string::npos)
std::cout << "The word '" << word << "' has been found in line " << line;
}
file.close();
}
else
{
std::cerr << "Error! File not found!\n";
return 1;
}
}
如果这不能解决您的问题,请发表评论,我会帮助您通过改进我的解决方案,直到你的问题得到解决。
干杯,
AH
If this did not solve your problem then please leave a comment and I will assist you by improving my solution until your problem gets solved.
Cheers,
AH
这篇关于如何逐行检查txt文件中的单词,何时找到打印整行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!