C++ 如何在文本文件中搜索单词,如果找到则打印整行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22800879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:13:37  来源:igfitidea点击:

How to search for a word in a text file and if found print out the entire line

c++iostring-matching

提问by Darius

My program needs to search for a word in a text file, and if it finds that word, to print out/display the entire line. Example:

我的程序需要在文本文件中搜索一个单词,如果找到该单词,则打印出/显示整行。例子:

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:

程序搜索文本accountant。当它找到它时,它返回以下内容:

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;
 }

回答by Kevin

Easy answer:

简单回答:

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;
}

In general, avoid mixing <<and getlinetogether when reading from a streamas it causes strange issues with line endings.

一般来说,从 a 读取时避免混合<<getline在一起,stream因为它会导致行尾出现奇怪的问题。