How to print the log line containing a specific date from a text block in C++

2 Answers

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

// Function that prints the matching log line

void printLogByDate(const std::string& logs, const std::string& targetDate) {
    std::istringstream stream(logs);
    std::string line;

    while (std::getline(stream, line)) {
        if (line.find(targetDate) != std::string::npos) {
            std::cout << line << std::endl;
            return; // stop after first match
        }
    }

    std::cout << "Date not found." << std::endl;
}

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"
        "26/01/2016 - Log entry ten.\n";

    printLogByDate(logs, "05/11/2024");
}



/*
run:

05/11/2024 - Log entry four.

*/

 



answered 6 hours ago by avibootz
0 votes
#include <iostream>
#include <sstream>
#include <string>

// Function that returns the matching line

std::string findLogByDate(const std::string& logs, const std::string& targetDate) {
    std::istringstream stream(logs);
    std::string line;

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

    return ""; // empty string means "not found"
}

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"
        "26/01/2016 - Log entry ten.\n";

    std::string result = findLogByDate(logs, "05/11/2024");

    if (!result.empty()) {
        std::cout << result << std::endl;
    } else {
        std::cout << "Date not found." << std::endl;
    }
}



/*
run:

05/11/2024 - Log entry four.

*/

 



answered 6 hours ago by avibootz
...