Dar*_*us 8 c++ io string-matching
我的程序需要在文本文件中搜索单词,如果找到该单词,则打印/显示整行.例:
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 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;
}
Run Code Online (Sandbox Code Playgroud)
在一般情况下,避免混合<<并getline从阅读在一起时stream,因为它会导致行尾奇怪的问题.