我的程序需要在文本文件中搜索一个词,如果找到该词,则打印/显示整行。示例:
employee name date joined position project annual salary tom jones 1/13/2011 accountant pricing 55000 Susan lee 2/5/2007 Manager policy 70000
User enters a search word:
accountant
Program searches text for accountant
. When it finds it, it returns the following:
employee name date joined position project annual salary tom jones 1/13/2011 accountant pricing 55000
This is the code I came up with but it doesn't work.
void KeyWord(ifstream &FileSearch)
{
string letters;
int position =-1;
string line;
ifstream readSearch;
cout<<"enter search word ";
cin>>letters;
"\n";
FileSearch.open("employee");
if(FileSearch.is_open())
{
while(getline(FileSearch, line))
{
FileSearch>>line;
cout<<line<<endl;
position=line.find(letters,position+1);
if(position==string::npos);
if(FileSearch.eof())
break;
cout<<line<<endl;
}
}
cout<<"Cant find"<<letters<<endl;
}
最佳答案
简单的回答:
void Keyword(ifstream & stream, string token) {
string line;
while (getline(stream, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
}
}
cout << token << " not found" << endl;
}
一般来说,避免混合<<
和 getline
一起阅读 stream
因为它会导致行尾出现奇怪的问题。
关于c++ - 如何在文本文件中搜索单词,如果找到则打印出整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800879/