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

标签 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

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/

相关文章:

c++ - 调整窗口大小时不断发送窗口消息 WM_SIZING

c++ - 如何获得指向颜色按钮的指针

linux - Sync IO 在较新的 Linux 内核上慢得令人难以置信

javascript - 可以使用通配符调用 Javascript 中的变量吗?

r - 匹配 R 中给定向量中的一系列单个或多个单词

c++ - 通过静态函数增加非静态变量

c++ - OpenCV 错误 : "LNK1181: cannot open file ' opencv_flann310. 库'”

C++ 二进制流

bash - 相当于 `getrusage()` 的命令行

Java搜索字符串内容以进行部分匹配