我的程序需要在文本文件中搜索单词,如果找到该单词,则打印/显示整行。例如:
employee name date joined position project annual salary tom jones 1/13/2011 accountant pricing 55000 Susan lee 2/5/2007 Manager policy 70000
用户输入搜索字词:
会计师
程序搜索accountant
的文字。当它找到它时,它返回以下内容:
employee name date joined position project annual salary tom jones 1/13/2011 accountant pricing 55000
这是我提出的代码,但它没有用。
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;
}
答案 0 :(得分:14)
简单回答:
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
混合在一起,因为它会导致行结尾的奇怪问题。