如何在C ++中从文本文件中进行多次搜索? [英] How Do I Do Multiple Searches From A Text File In C++?
问题描述
所以,这是我试图编写的程序 - 用户将有机会输入字符串,字符串将与存储在文本文件中的字符串匹配。什么时候,我试过它,它工作正常,并没有显示任何问题。现在,我想扭曲程序一点,并希望给用户多次机会从数据库中搜索一个单词。这是程序开始向我显示错误的地方。我将程序放在一个循环中,并尝试给用户两次搜索数据库中的单词。问题是当我运行程序时,它只在第二次第一次工作,其余时间不在数据库中搜索单词。我不知道问题出在哪里。请任何人都可以建议我。这是我的代码。
我正在寻找的文本文件包含以下内容(Hello World,嘿)。
So, this is the program i tried to write- The user will be given a chance to enter a string and the string will be matched with the string stored in a text file. When, i tried it, it worked fine and showed no problems. Now, i wanted to twist the program a bit and wanted to give the user multiple chances to search for a word from the database. This is where the program started showing me errors. I placed the program in a loop and tried to give the user two times to search for a word in the database. The problem is when i run the program, it only works for the first time the second time and the remaining times it doesn't search for the word in the database. I don't know where the problem is. Please can anyone suggest me anything. Here is my code.
My text file which i am looking for contains the following (Hello World, Hey).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string search,line;
ifstream read;
int i =0;
while(i<2)
{
read.open("type.txt");
cout<<"Enter the word to search"<<endl;
cin>>search;
size_t pos;
if(read.is_open())
{
while (getline(read,line))
{
pos = line.find(search);
if(pos != string::npos)
{
cout<<line<<endl;
}
}
}
i++;
}
system("pause");
}
推荐答案
while循环应测试ifstream是否为eof或使用good()时出错。 getline只返回文件流而不是布尔表达式。
The while loop should test if the ifstream is at eof or an error using good(). getline only returns the file stream not a boolean expression.
int main()
{
string _search;
string line;
ifstream read;
int i =0;
while(i++<2)
{
cout<<"Enter the word to search"<<endl;
cin>>_search;
read.open("type.txt");
size_t pos,i=0;
if(read.is_open())
{
while (read.good())
{
i++;
getline(read,line);
pos = line.find(_search);
if(pos != string::npos)
{
cout<<i<<": "<<line<<endl;
}
else
{
cout<<"Not found"<<endl;
}
}
read.close();
}
}
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string search,line;
ifstream read;
int i =0;
while(i<2)
{
read.open("type.txt");
cout<<"Enter the word to search"<<endl;
cin>>search;
size_t pos;
if(read.is_open())
{
while (getline(read,line))
{
pos = line.find(search);
if(pos != string::npos)
{
cout<<line<<endl;
read.close();
}
}
}
i++;
}
system("pause");
}
这篇关于如何在C ++中从文本文件中进行多次搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!