How to print all log lines containing a specific date from a text block in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

// find all log lines with a given date

std::vector<std::string> findAllLogsByDate(const std::string& logs,
                                           const std::string& targetDate) {
    std::istringstream stream(logs);
    std::string line;
    std::vector<std::string> matches;

    while (std::getline(stream, line)) {
        if (line.find(targetDate) != std::string::npos) {
            matches.push_back(line);
        }
    }

    return matches;
}

int main() {
    std::string logs =
        "01/12/2023 - Log entry one.\n"
        "17/03/2021 - Log entry two.\n"
        "29/07/2019 - Log entry three.\n"
        "05/11/2024 - Log entry four.\n"
        "22/08/2020 - Log entry five.\n"
        "14/02/2018 - Log entry six.\n"
        "30/09/2022 - Log entry seven.\n"
        "11/06/2017 - Log entry eight.\n"
        "03/04/2025 - Log entry nine.\n"
        "05/11/2024 - Log entry ten.\n";

    auto results = findAllLogsByDate(logs, "05/11/2024");

    for (const auto& r : results) {
        std::cout << r << std::endl;
    }
}



/*
run:

05/11/2024 - Log entry four.
05/11/2024 - Log entry ten.

*/

 



answered 5 hours ago by avibootz
...