Reading parts of a line (getline())

我是研究僧i 提交于 2019-12-11 15:26:10

问题


Basically this program searches a .txt file for a word and if it finds it, it prints the line and the line number. Here is what I have so far.

Code:

#include "std_lib_facilities.h"

int main()
{
    string findword;
    cout << "Enter word to search for.\n";
    cin >> findword;

    char filename[20];
    cout << "Enter file to search in.\n";
    cin >> filename;
    ifstream ist(filename);

    string line;
    string word;
    int linecounter = 1;
    while(getline(ist, line))
    {
     if(line.find(findword) != string::npos){
             cout << line << " " << linecounter << endl;}
     ++linecounter;
     }

     keep_window_open();
}

Solved.


回答1:


You're looking for find:

if (line.find(findword) != string::npos) { ... }



回答2:


I would do as you suggested and break the lines into words or tokens delimited by whitespace and then search for desired keywords amongst the list of tokens.




回答3:


Make sure there are no spaces around the names in your text file. Otherwise, let ist take care like the following :

while(ist >> line)
{
 if(line == findword){
         cout << line << " " << linecounter << endl;}
 ++linecounter;
 }

I believe that your names file contains a name on every line. so using >>, ist will take care if there are extra spaces.




回答4:


You could use a regular expression to find the word in the line. Don't know enough C++ to help you with the details.



来源:https://stackoverflow.com/questions/1185365/reading-parts-of-a-line-getline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!