1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <fstream>
#include <iostream>
#include <limits>
#include <regex>
#include <string>
#include <utility>
#include <vector>
std::pair<int, std::vector<std::string>>
fillWithMatches(std::ifstream& source,
std::vector<std::string>& matches,
const std::string& searched);
void waitForEnter();
int main()
{
bool again {false};
do {
std::cout << "Please give me the word to be found (no spaces!): ";
std::string tobefound;
std::cin >> tobefound;
std::string filename("short.txt");
std::ifstream infile(filename);
std::vector<std::string> matches;
auto result = fillWithMatches(infile, matches, tobefound);
std::cout << "\nFound " << result.first << " matches in "
<< matches.size() << " lines.\nDetails:\n";
for(const auto& s : result.second) { std::cout << "--> " << s << '\n'; }
infile.close();
std::cout << "\nDo you want to perform another check [y, n]? ";
char answer {'n'};
std::cin >> answer;
std::cin.ignore(1);
if('y' == answer) { again = true; }
else { again = false; }
} while(again);
waitForEnter();
return 0;
}
std::pair<int, std::vector<std::string>>
fillWithMatches(std::ifstream& source,
std::vector<std::string>& matches,
const std::string& searched)
{
std::pair<int, std::vector<std::string>> result;
std::string line;
std::regex reg("\\b" + searched + "\\b",
std::regex_constants::ECMAScript | std::regex_constants::icase);
while(std::getline(source, line)) {
auto sbegin = std::sregex_iterator(line.begin(), line.end(), reg);
auto send = std::sregex_iterator();
if(0 < std::distance(sbegin, send)) {
result.first += std::distance(sbegin, send);
matches.push_back(line);
for(std::sregex_iterator i{sbegin}; i!=send; ++i) {
std::smatch sm = *i;
std::cout << sm.prefix() << " --> " << sm.str() << '\n';
}
}
}
result.second = matches;
return result;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|