【问题标题】:How to search for a word in a text file and if found print out the entire line如何在文本文件中搜索单词,如果找到则打印出整行
【发布时间】:2014-05-13 02:41:31
【问题描述】:

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

员工姓名 入职日期 项目 年薪 汤姆琼斯 1/13/2011 会计师定价 55000 Susan lee 2/5/2007 经理政策 70000

用户输入搜索词:

会计

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

员工姓名 入职日期 项目 年薪 汤姆琼斯 1/13/2011 会计师定价 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;
 }

【问题讨论】:

    标签: c++ io string-matching


    【解决方案1】:

    简单回答:

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

    一般来说,从stream 读取时,请避免将&lt;&lt;getline 混合在一起,因为这会导致行尾出现奇怪的问题。

    【讨论】:

    • 谢谢,我现在就试试这个。并重新发布结果或问题。我猜你在哪里有令牌这个词。我要用字母替换。我在哪里得到输入来自用户..?
    • 更新,因为我刚刚注意到一个错误。 if 语句应该有一个 != string::npos。是的,只需将字符串标记替换为您要查找的任何内容(示例中为会计师)
    • 完美的工作......非常感谢......凯文......我真的很感激......我们最好的家伙......再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多