问题
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