Skip to content

Instantly share code, notes, and snippets.

@kLiHz
Last active May 12, 2021 15:40
Show Gist options
  • Save kLiHz/b889fc5db3029f23e30af3158f390f34 to your computer and use it in GitHub Desktop.
Save kLiHz/b889fc5db3029f23e30af3158f390f34 to your computer and use it in GitHub Desktop.
Find word in a file.
Next to a great forest there lived a poor woodcutter with his wife and his two children.
The boy's name was Hansel and the girl's name was Gretel. He had but little to eat, and
once, when a great famine came to the land, he could no longer provide even their daily
bread.
One evening as he was lying in bed worrying about his problems, he sighed and said to his
wife, "What is to become of us? How can we feed our children when we have nothing for
ourselves?"
"Man, do you know what?" answered the woman. "Early tomorrow morning we will take the two
children out into the thickest part of the woods, make a fire for them, and give each of
them a little piece of bread, then leave them by themselves and go off to our work. They
will not find their way back home, and we will be rid of them."
"No, woman," said the man. "I will not do that. How could I bring myself to abandon my
own children alone in the woods? Wild animals would soon come and tear them to pieces."
#include <string>
#include <iostream>
#include <fstream>
int main() {
std::ifstream inFile("passage.txt");
std::string needle;
std::cout << "Enter your keyword: ";
std::cin >> needle;
std::string line;
int line_number = 0;
int cnt = 0;
while (!inFile.eof()) {
std::getline(inFile, line);
++line_number;
int pos = 0;
while ((pos = line.find(needle, pos)) != std::string::npos) {
++cnt;
std::cout << "Found '" << needle << "' at line " << line_number << ", time " << cnt << ": ";
// show words before and after the keyword
std::string context;
size_t begin = 0, end_pos = line.length();
const int padding = 15;
if (pos - padding > 0) {
context += "...";
begin = pos - padding;
}
if (pos + needle.length() + padding < line.length()) {
end_pos = pos + needle.length() + padding;
}
int i = begin;
for (; i < end_pos; ++i) {
if (i == pos) context += "\033[32m";
context += line[i];
if (i == pos + needle.length() - 1) context += "\033[0m";
}
if (i < line.length()) context += "...";
std::cout << context << "\n"; // show the context
pos += needle.length();
}
}
inFile.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment