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.
您正在寻找find
:
if (line.find(findword) != string::npos) { ... }
我会按照您的建议进行操作,然后将行分成由空格分隔的单词或标记,然后在标记列表中搜索所需的关键字。
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.
You could use a regular expression to find the word in the line. Don't know enough C++ to help you with the details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.